<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  
  <meta name="renderer" content="webkit">
  <meta http-equiv="X-UA-Compatible" content="IE=edge" >
  <link rel="dns-prefetch" href="https://blog.elfred.top">
  <title>系统设计面试题 | Elfred&#39;s Blog</title>
  <meta name="generator" content="hexo-theme-yilia-plus">
  <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
  
  <meta property="og:type" content="article">
<meta property="og:title" content="系统设计面试题">
<meta property="og:url" content="https://blog.elfred.top/2022/05/21/internet/DESIGN/index.html">
<meta property="og:site_name" content="Elfred&#39;s Blog">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="https://tva1.sinaimg.cn/large/008eGmZEly1gne4vx9hu4j30x60gw0w5.jpg">
<meta property="og:image" content="https://i.loli.net/2021/02/20/7hx2RcvUPKgXpma.png">
<meta property="og:image" content="https://tva1.sinaimg.cn/large/008i3skNly1gq6ijej9w7j30p00doaim.jpg">
<meta property="og:image" content="https://tva1.sinaimg.cn/large/008i3skNly1gq6iiju6h8j30ry0o6dj0.jpg">
<meta property="og:image" content="https://tva1.sinaimg.cn/large/008i3skNly1gq6ijuqesxj30ke0ekgpj.jpg">
<meta property="og:image" content="https://tva1.sinaimg.cn/large/008i3skNly1gq6il759apj313s068abj.jpg">
<meta property="og:image" content="https://tva1.sinaimg.cn/large/008i3skNly1gq6ilvuhupj30ye08e0vd.jpg">
<meta property="og:image" content="https://tva1.sinaimg.cn/large/008i3skNly1gq6imu2khlj31080gu0xc.jpg">
<meta property="og:image" content="https://tva1.sinaimg.cn/large/008i3skNly1gq6ingki0yj30kw0d6gmr.jpg">
<meta property="og:image" content="https://tva1.sinaimg.cn/large/008i3skNly1gq6inzsk9xj30lg0cign1.jpg">
<meta property="og:image" content="https://tva1.sinaimg.cn/large/008i3skNly1gq6iogl9x0j30ja0cqdh7.jpg">
<meta property="og:image" content="https://tva1.sinaimg.cn/large/008i3skNly1gq6ioxthajj30ii0cemyk.jpg">
<meta property="og:image" content="https://tva1.sinaimg.cn/large/008i3skNly1gq6ipcc12jj30lg0coabe.jpg">
<meta property="og:image" content="https://tva1.sinaimg.cn/large/008i3skNly1gq6ipob6wjj30we0i4jz2.jpg">
<meta property="og:image" content="https://tva1.sinaimg.cn/large/008i3skNly1gq6iq4xdjtj30q407egnk.jpg">
<meta property="og:image" content="https://tva1.sinaimg.cn/large/008i3skNly1gq6iqnas8fj31400lkaj2.jpg">
<meta property="og:image" content="https://tva1.sinaimg.cn/large/008i3skNly1gq6ir0d0cmj30qw0hw41z.jpg">
<meta property="og:image" content="https://tva1.sinaimg.cn/large/008i3skNly1gq6ir0d0cmj30qw0hw41z.jpg">
<meta property="og:image" content="https://tva1.sinaimg.cn/large/008i3skNly1gq6irlptv0j30z408wabn.jpg">
<meta property="og:image" content="https://tva1.sinaimg.cn/large/008i3skNly1gq6j1t85zuj31020ds42m.jpg">
<meta property="og:image" content="https://tva1.sinaimg.cn/large/008i3skNly1gq6j26fh88j30ni0ea41c.jpg">
<meta property="og:image" content="https://tva1.sinaimg.cn/large/008i3skNly1gq6j2m0rr1j30ly0iugnk.jpg">
<meta property="og:image" content="https://tva1.sinaimg.cn/large/008i3skNly1gq6j3160yuj30rw0eo77o.jpg">
<meta property="og:image" content="https://tva1.sinaimg.cn/large/008i3skNly1gq6j3160yuj30rw0eo77o.jpg">
<meta property="og:image" content="https://tva1.sinaimg.cn/large/008i3skNly1gx2u1jn9b3j31e80hqjt5.jpg">
<meta property="og:image" content="https://tva1.sinaimg.cn/large/008i3skNly1gq6jlghxe0j30t00fsjtw.jpg">
<meta property="og:image" content="https://tva1.sinaimg.cn/large/008i3skNly1gq6jm8q3yej311c0h6q7v.jpg">
<meta property="og:image" content="https://tva1.sinaimg.cn/large/008i3skNly1gq6jmqtl1hj30q60dmtck.jpg">
<meta property="og:image" content="https://tva1.sinaimg.cn/large/008i3skNly1gq6jmyxnylj30ns06adgu.jpg">
<meta property="og:image" content="https://tva1.sinaimg.cn/large/008i3skNly1gq6jncecy1j30yy0eejtq.jpg">
<meta property="og:image" content="https://tva1.sinaimg.cn/large/0081Kckwly1gm4umi0759j30hi0a03zd.jpg">
<meta property="og:image" content="https://tva1.sinaimg.cn/large/0081Kckwly1gm4ux5gohpj30hs0ajjs1.jpg">
<meta property="og:image" content="https://tva1.sinaimg.cn/large/008i3skNly1gq6jnu8l6aj315k060wfi.jpg">
<meta property="og:image" content="https://tva1.sinaimg.cn/large/008i3skNly1gq6jo7abpbj30wi0ciacs.jpg">
<meta property="og:image" content="https://tva1.sinaimg.cn/large/008i3skNly1gq6jofq9r4j315i0fmq96.jpg">
<meta property="og:image" content="https://tva1.sinaimg.cn/large/008eGmZEly1goqpbvl5pvj30qu0gcgm0.jpg">
<meta property="og:image" content="https://tva1.sinaimg.cn/large/008eGmZEly1goqpc3hz9dj31450ggq8k.jpg">
<meta property="og:image" content="https://tva1.sinaimg.cn/large/0081Kckwly1glvl9c3hp2j30py0d7q4i.jpg">
<meta property="og:image" content="https://tva1.sinaimg.cn/large/008i3skNly1gq6j9dkq6vj30w20kowku.jpg">
<meta property="og:image" content="https://tva1.sinaimg.cn/large/008i3skNly1gq6ja736ekj316o06640u.jpg">
<meta property="og:image" content="https://tva1.sinaimg.cn/large/0081Kckwly1gluq6vlvglj30nw0e076f.jpg">
<meta property="og:image" content="https://tva1.sinaimg.cn/large/008i3skNly1gq6japwof2j31520na4mh.jpg">
<meta property="og:image" content="https://tva1.sinaimg.cn/large/0081Kckwly1gm8kxci29zj30b305974z.jpg">
<meta property="og:image" content="https://tva1.sinaimg.cn/large/0081Kckwly1gm8jswr3poj30hh078dg2.jpg">
<meta property="og:image" content="https://tva1.sinaimg.cn/large/0081Kckwly1gm8m1ge2ksj30j707gt96.jpg">
<meta property="og:image" content="https://tva1.sinaimg.cn/large/008i3skNly1gq6jc1stt3j31380lswso.jpg">
<meta property="og:image" content="https://tva1.sinaimg.cn/large/008eGmZEly1gn9kwux9vjj312w0li138.jpg">
<meta property="og:image" content="https://static-aliyun-doc.oss-accelerate.aliyuncs.com/assets/img/zh-CN/3199158061/p132750.png">
<meta property="og:image" content="https://tva1.sinaimg.cn/large/008eGmZEly1goboitd4h2j30u00ciq3i.jpg">
<meta property="og:image" content="https://tva1.sinaimg.cn/large/008eGmZEly1gobohzda8fj30u00cgaax.jpg">
<meta property="og:image" content="https://i.loli.net/2021/01/25/zjwC7B8fdcpDytA.png">
<meta property="og:image" content="https://i.loli.net/2021/01/25/GITnbhDqPdtZY2k.png">
<meta property="og:image" content="https://i.loli.net/2021/01/25/Lo5N8QYlI2DPjyO.png">
<meta property="og:image" content="https://tva1.sinaimg.cn/large/008eGmZEly1gobogaxxjkj304v0e7t93.jpg">
<meta property="og:image" content="https://tva1.sinaimg.cn/large/008i3skNly1gq6jd95rpij315g0hqn5q.jpg">
<meta property="og:image" content="https://tva1.sinaimg.cn/large/008eGmZEly1gmqv8zyhkqj311s0u0q7s.jpg">
<meta property="og:image" content="https://tva1.sinaimg.cn/large/008eGmZEly1goruh4oifej30xq0auq7p.jpg">
<meta property="og:image" content="https://tva1.sinaimg.cn/large/008eGmZEly1goruqql81gj30p20c5q45.jpg">
<meta property="og:image" content="https://pic1.zhimg.com/80/v2-13cab4d5f56e3ecb682c351c0eb4a24b_1440w.jpg?source=1940ef5c">
<meta property="og:image" content="https://tva1.sinaimg.cn/large/008eGmZEly1goruu4homyj31400ht405.jpg">
<meta property="og:image" content="https://tva1.sinaimg.cn/large/008i3skNly1gq6jet6kizj310c0ngtp4.jpg">
<meta property="article:published_time" content="2022-05-21T03:24:00.000Z">
<meta property="article:modified_time" content="2022-05-23T09:20:29.776Z">
<meta property="article:author" content="Elfred">
<meta property="article:tag" content="面经">
<meta property="article:tag" content="面试题">
<meta property="article:tag" content="系统设计">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="https://tva1.sinaimg.cn/large/008eGmZEly1gne4vx9hu4j30x60gw0w5.jpg">
  
    <link rel="alternative" href="/atom.xml" title="Elfred&#39;s Blog" type="application/atom+xml">
  
  
    <link rel="icon" href="/favicon.ico">
  
  
    <link rel="apple-touch-icon" href="/apple-touch-icon-180x180.png">
  
  <link rel="stylesheet" type="text/css" href="/./main.a5fda8.css">
  <style type="text/css">
    
    #container.show {
      background: linear-gradient(200deg,#a0cfe4,#e8c37e);
    }
  </style>
  

  

  
    
 	  <script src="/lib/clickLove.js"></script>
  
  


  

</head>

<body>
  <div id="container" q-class="show:isCtnShow">
    <canvas id="anm-canvas" class="anm-canvas"></canvas>
    <div class="left-col" q-class="show:isShow">
      


<div class="overlay" style="background: #4d4d4d;background: url('/img/biubiubiu.gif') no-repeat ;"></div>
<div class="intrude-less">
	<header id="header" class="inner">
		<a href="/" class="profilepic">
			<img src="/images/avatar.jpg" class="js-avatar">
		</a>
		<hgroup>
			<h1 class="header-author"><a href="/">Elfred</a></h1>
		</hgroup>
		
		<p class="header-subtitle">上善若水</p>
		

		<nav class="header-menu">
			<ul>
			
				<li><a href="/" >主页</a></li>
			
				<li><a href="/tags/%E9%9D%A2%E7%BB%8F/" >面经</a></li>
			
			</ul>
		</nav>
		<nav class="header-smart-menu">
			
				
					<a q-on="click: openSlider(e, 'innerArchive')" href="javascript:void(0)">所有文章</a>
				
			
				
					<a q-on="click: openSlider(e, 'friends')" href="javascript:void(0)">友链</a>
				
			
				
					<a q-on="click: openSlider(e, 'aboutme')" href="javascript:void(0)">关于我</a>
				
			
		</nav>
		<nav class="header-nav">
			<div class="social">
				
					
						<a class="github" href="https://github.com/kuqi007" 
												title="GitHub" target="_blank"><i class="icon-github"></i></a>
					
				
					
						<a class="mail" href="mailto:elfred2096@outlook.com" 
												title="邮件联系" target="_blank"><i class="icon-mail"></i></a>
					
				
			</div>
		
			
			
			
			
			<div>
				<iframe frameborder="no" border="0" marginwidth="0" marginheight="0" width="240" height="86" src="//music.163.com/outchain/player?type=2&id=435305771&auto=1&height=66"></iframe>
			</div>
			
				
				<p style="font-size: 12px;">这似乎是首纯音乐，请尽情的欣赏它吧！<p>
			
		
		</nav>
	</header>		
</div>

    </div>
    <div class="mid-col" q-class="show:isShow,hide:isShow|isFalse">
      
      
      <a class="forkMe" style="position:absolute;z-index:999;top:0;right:0.5em;" 
        href="https://github.com/JoeyBling/hexo-theme-yilia-plus" target="_blank">
        <img src="/img/forkme.png"
          class="attachment-full size-full" alt="Fork me on GitHub" data-recalc-dims="1"></a>
      
      
<nav id="mobile-nav">
  	<div class="overlay js-overlay" style="background: #4d4d4d"></div>
	<div class="btnctn js-mobile-btnctn">
  		<div class="slider-trigger list" q-on="click: openSlider(e)"><i class="icon icon-sort"></i></div>
	</div>
	<div class="intrude-less">
		<header id="header" class="inner">
			<div class="profilepic">
				<a href="/">
					<img src="/images/avatar.jpg" class="js-avatar">
				</a>
			</div>
			<hgroup>
			  <h1 class="header-author js-header-author">Elfred</h1>
			</hgroup>
			
			<p class="header-subtitle"><i class="icon icon-quo-left"></i>上善若水<i class="icon icon-quo-right"></i></p>
			
			
			
				
			
				
			
			
			
			<nav class="header-nav">
				<div class="social">
					
						
						<a class="github" target="_blank" 
							href="https://github.com/kuqi007" title="GitHub"><i class="icon-github"></i></a>
						
					
						
						<a class="mail" target="_blank" 
							href="mailto:elfred2096@outlook.com" title="邮件联系"><i class="icon-mail"></i></a>
						
					
				</div>
			</nav>

			<nav class="header-menu js-header-menu">
				<ul style="width: 50%">
				
				
					<li style="width: 50%"><a href="/">主页</a></li>
		        
					<li style="width: 50%"><a href="/tags/%E9%9D%A2%E7%BB%8F/">面经</a></li>
		        
				</ul>
			</nav>
		</header>				
	</div>
	<div class="mobile-mask" style="display:none" q-show="isShow"></div>
</nav>

      <div id="wrapper" class="body-wrap">
        <div class="menu-l">
          <div class="canvas-wrap">
            <canvas data-colors="#eaeaea" data-sectionHeight="100" data-contentId="js-content" id="myCanvas1"
              class="anm-canvas"></canvas>
          </div>
          <div id="js-content" class="content-ll">
            <article id="post-internet/DESIGN" class="article article-type-post " itemscope itemprop="blogPost">
  <div class="article-inner">
    
      <header class="article-header">
  
  
    <h1 class="article-title" itemprop="name">
      系统设计面试题
    </h1>
  


  
  
        
        <span id="busuanzi_container_page_pv" style='display:none' class="archive-article-date">
              <i class="icon-smile icon"></i> 阅读数：<span id="busuanzi_value_page_pv"></span>次
        </span>

<a href="/2022/05/21/internet/DESIGN/" class="archive-article-date">
        <time datetime="2022-05-21T03:24:00.000Z" itemprop="datePublished"><i class="icon-calendar icon"></i>2022-05-21</time>
</a>

  
  
    
<div style="margin-top:10px;">
  <span class="post-time">
    <span class="post-meta-item-icon">
      <!-- fonts.scss -->
      <!-- 百度字体平台:http://fontstore.baidu.com/static/editor/index.html -->
      <i class="icon-statistics"></i>
      <span class="post-meta-item-text"> 字数统计:</span>
      <span class="post-count">46.1k字</span>
    </span>
  </span>

  <span class="post-time">
    &nbsp; | &nbsp;
    <span class="post-meta-item-icon">
      <i class="icon-book icon"></i>
      <span class="post-meta-item-text"> 阅读时长≈</span>
      <span class="post-count">177分</span>
    </span>
  </span>
</div>


  
  </header>
  
  <div class="article-entry" itemprop="articleBody">
    
    <hr>
<span id="more"></span>


<h1 id="一、ES篇"><a href="#一、ES篇" class="headerlink" title="一、ES篇"></a>一、ES篇</h1><blockquote>
<p>Elasticsearch可以实现<strong>秒级</strong>的搜索，cluster是一种分布式的部署，极<strong>易扩展(scale )<strong>这样很容易使它处理PB级的数据库容量。最重要的是Elasticsearch是它搜索的结果可以按照分数进行排序，它能提供我们最</strong>相关</strong>的搜索结果（<strong>relevance</strong>) 。</p>
</blockquote>
<h2 id="1、概述"><a href="#1、概述" class="headerlink" title="1、概述"></a>1、概述</h2><h3 id="特点"><a href="#特点" class="headerlink" title="特点"></a>特点</h3><ol>
<li><p><strong>安装方便</strong>：没有其他依赖，下载后安装非常方便；只用修改几个参数就可以搭建起来一个集群</p>
</li>
<li><p><strong>JSON</strong>：输入&#x2F;输出格式为 JSON，意味着不需要定义 Schema，快捷方便</p>
</li>
<li><p><strong>RESTful</strong>：基本所有操作 ( 索引、查询、甚至是配置 ) 都可以通过 HTTP 接口进行</p>
</li>
<li><p><strong>分布式</strong>：节点对外表现对等（每个节点都可以用来做入口） 加入节点自动负载均衡</p>
</li>
<li><p><strong>多租户</strong>：可根据不同的用途分索引，可以同时操作多个索引</p>
</li>
<li><p><strong>支持超大数据</strong>： 可以扩展到 PB 级的结构化和非结构化数据 海量数据的近实时处理</p>
</li>
</ol>
<h3 id="功能"><a href="#功能" class="headerlink" title="功能"></a>功能</h3><ul>
<li><p><strong>分布式的搜索引擎</strong></p>
<p>分布式：Elasticsearch自动将海量数据分散到多台服务器上去存储和检索</p>
</li>
<li><p><strong>全文检索</strong></p>
<p>提供模糊搜索等自动度很高的查询方式，并进行相关性排名，高亮等功能</p>
</li>
<li><p><strong>数据分析引擎（分组聚合）</strong></p>
<p>社区网站，最近一周用户登录、最近一个月各功能使用情况</p>
</li>
<li><p><strong>对海量数据进行近实时（秒级）的处理</strong></p>
<p>海量数据的处理：因为是分布式架构，可以采用大量的服务器去存储和检索数据</p>
</li>
</ul>
<h3 id="场景"><a href="#场景" class="headerlink" title="场景"></a>场景</h3><ul>
<li><p><strong>搜索类</strong>场景</p>
<p>比如说人员检索、设备检索、App内的搜索、订单搜索。</p>
</li>
<li><p><strong>日志分析</strong>类场景</p>
<p>经典的ELK组合（<strong>Elasticsearch</strong>&#x2F;<strong>Logstash</strong>&#x2F;<strong>Kibana</strong>），实现<strong>日志收集</strong>，<strong>日志存储</strong>，<strong>日志分析</strong></p>
</li>
<li><p><strong>数据预警平台</strong>及数据分析场景</p>
<p>例如社区团购提示，当优惠的价格低于某个值时，自动触发通知消息，通知用户购买。</p>
<p>分析竞争对手商品销量Top10，供运营分析等等。</p>
</li>
<li><p>**商业BI(Business Intelligence)**系统</p>
<p>比如社区周边，需要分析某一地区用户消费金额及商品类别，输出相应的报表数据，并预测该地区的热卖商品，通过区域和人群特征划分进行定向推荐。Elasticsearch执行数据分析和挖掘，Kibana做数据可视化。</p>
</li>
</ul>
<h3 id="竞品分析"><a href="#竞品分析" class="headerlink" title="竞品分析"></a>竞品分析</h3><p><strong>Lucene</strong></p>
<p>Java编写的信息搜索工具包（Jar包），Lucene只是一个框架，熟练运用Lucene非常复杂。</p>
<p><strong>Solr</strong></p>
<p>基于<strong>Lucene</strong>的HTTP接口查询服务器，是一个封装了很多Lucene细节搜索引擎系统</p>
<p><strong>Elasticsearch</strong></p>
<p>基于<strong>Lucene</strong>分布式海量数据近实时搜索引擎。采用的策略是将每一个字段都编入索引，使其可以被搜索。</p>
<h3 id="对比"><a href="#对比" class="headerlink" title="对比"></a>对比</h3><p>1）Solr利用Zookeeper进行分布式管理，而Elasticsearch自身带有分布式协调管理功能</p>
<p>2）Solr比Elasticsearch实现更加全面，而Elasticsearch本身更注重于核心功能， 高级功能多由第三方插件提供</p>
<p>3）Solr在传统的搜索应用中表现好于Elasticsearch，而Elasticsearch在实时搜索应用方面比Solr表现好</p>
<p>目前主流依然是<strong>Elasticsearch</strong>7.x 最新的是7.8</p>
<p>​	优化：<strong>默认集成JDK</strong>、升级Lucene8大幅提升<strong>TopK性能</strong>、引入熔断机制<strong>避免OOM</strong>发生</p>
<h2 id="2、基本概念"><a href="#2、基本概念" class="headerlink" title="2、基本概念"></a>2、基本概念</h2><h3 id="IK分词器"><a href="#IK分词器" class="headerlink" title="IK分词器"></a>IK分词器</h3><p>IKAnalyzer是一个开源的，基于java语言开发的轻量级的中文分词工具包。新版本的IKAnalyzer3.0则发展为 面向Java的公用分词组件，独立于Lucene项目，同时提供了对Lucene的默认优化实现。</p>
<p>IK分词器3.0的特性如下：</p>
<ol>
<li>采用了特有的“正向迭代<strong>最细粒度</strong>切分算法“，具有<strong>60万</strong>字&#x2F;秒的高速处理能力。</li>
<li>采用了<strong>多子处理器</strong>分析模式，支持：英文字母（IP地址、Email、URL）、数字（日期，常用中文数量词，罗马数字，科学计数法），中文词汇（姓名、地名处理）等分词处理。</li>
<li>支持<strong>个人词条的优化</strong>的词典存储，更小的内存占用。</li>
<li>针对Lucene<strong>全文检索优化</strong>的查询分析器IKQueryParser；采用歧义分析算法优化查询关键字的搜索</li>
<li>排列组合，能极大的提高Lucene检索的命中率。</li>
</ol>
<ul>
<li><strong>扩展词典</strong>：ext_dict </li>
<li><strong>停用词典</strong>：stop_dict</li>
<li><strong>同义词典</strong>：same_dict</li>
</ul>
<h3 id="索引（类数据库）"><a href="#索引（类数据库）" class="headerlink" title="索引（类数据库）"></a>索引（类数据库）</h3><p>settings：设置索引库，定义索引库的分片数副本数等</p>
<h3 id="映射（类表设计）"><a href="#映射（类表设计）" class="headerlink" title="映射（类表设计）"></a>映射（类表设计）</h3><ul>
<li>字段的数据类型</li>
<li>分词器类型</li>
<li>是否要进行存储或者创造索引</li>
</ul>
<h3 id="文档（数据）"><a href="#文档（数据）" class="headerlink" title="文档（数据）"></a>文档（数据）</h3><ul>
<li>全量更新用Put</li>
<li>局部更新用Post</li>
</ul>
<h2 id="3、高级特性"><a href="#3、高级特性" class="headerlink" title="3、高级特性"></a>3、高级特性</h2><h3 id="映射高级"><a href="#映射高级" class="headerlink" title="映射高级"></a>映射高级</h3><h4 id="地理坐标点数据类型"><a href="#地理坐标点数据类型" class="headerlink" title="地理坐标点数据类型"></a><strong>地理坐标点数据类型</strong></h4><blockquote>
<p>地理坐标点是指地球表面可以用经纬度描述的一个点。 地理坐标点可以用来计算两个坐标间的距离，还可以判断一个坐标是否在一个区域中。地理坐标点需要显式声明对应字段类型为 geo_point</p>
</blockquote>
<h4 id="动态映射"><a href="#动态映射" class="headerlink" title="动态映射"></a>动态映射</h4><blockquote>
<p>使用dynamic mapping 来确定字段的数据类型并自动把新的字段添加到类型映射</p>
</blockquote>
<h3 id="DSL高级"><a href="#DSL高级" class="headerlink" title="DSL高级"></a>DSL高级</h3><ul>
<li><p><strong>查询所有(match_all query)</strong></p>
</li>
<li><p><strong>全文搜索(full-text query)</strong></p>
<ul>
<li>匹配搜索(match query)</li>
<li>短语搜索(match phrase query)</li>
<li>默认查询(query string)</li>
<li>多字段匹配搜索(multi match query)</li>
</ul>
</li>
<li><p><strong>词条级搜索(term-level query)</strong></p>
<ul>
<li>精确搜索term</li>
<li>集合搜索idx</li>
<li>范围搜索range</li>
<li>前缀搜索prefix</li>
<li>通配符搜索wildcard</li>
<li>正则搜索regexp</li>
<li>模糊搜索fuzzy</li>
</ul>
</li>
<li><p>复合搜索</p>
</li>
<li><p>排序<strong>sort</strong>&amp;分页<strong>size</strong>&amp;高亮<strong>highLight</strong>&amp;批量<strong>bluk</strong></p>
</li>
</ul>
<h3 id="聚合分析"><a href="#聚合分析" class="headerlink" title="聚合分析"></a><strong>聚合分析</strong></h3><blockquote>
<p>聚合分析是数据库中重要的功能特性，完成对一个查询的数据集中数据的聚合计算，如：找出某字段（或计算表达式的结果）的最大值、最小值，计算和、平均值等</p>
</blockquote>
<ul>
<li>对一个数据集求最大、最小、和、平均值等指标的聚合，在ES中称为<strong>指标聚合</strong> <strong>metric</strong></li>
<li>对查询出的数据进行<strong>分桶</strong>group by，再在<strong>桶</strong>上进行指标<strong>桶聚合</strong> <strong>bucketing</strong></li>
</ul>
<h3 id="智能搜索"><a href="#智能搜索" class="headerlink" title="智能搜索"></a><strong>智能搜索</strong></h3><ul>
<li>Term Suggester</li>
<li>Phrase Suggester</li>
<li>Completion Suggester</li>
<li>Context Suggester</li>
</ul>
<p>如果<strong>Completion Suggester</strong>已经到了零匹配，可以猜测用户有输入错误，这时候可以尝试一下<strong>Phrase Suggester</strong>。如果还是未匹配则尝试<strong>Term Suggester</strong>。</p>
<p>精准程度上(<strong>Precision</strong>)看： <strong>Completion &gt; Phrase &gt; Term</strong>， 而召回率上(Recall)则反之。</p>
<p>从性能上看，Completion Suggester是最快的，如果能满足业务需求，只用Completion Suggester做前缀匹配是最理想的。 Phrase和Term由于是做倒排索引的搜索，相比较而言性能应该要低不少，应尽量控制Suggester用到的索引的数据量，最理想的状况是经过一定时间预热后，索引可以全量map到内存。</p>
<h2 id="4、实战"><a href="#4、实战" class="headerlink" title="4、实战"></a>4、实战</h2><h3 id="写优化"><a href="#写优化" class="headerlink" title="写优化"></a>写优化</h3><ul>
<li><p><strong>副本数量</strong>0</p>
<p>首次 初始化数据时，将副本设置为0，写入完毕再改回，避免了副本建立索引的过程</p>
</li>
<li><p><strong>自动生成id</strong></p>
<p>可以避免写前判断是否存在的过程</p>
</li>
<li><p><strong>合理使用分词器</strong></p>
<p>binary类型不适用，title和text使用不同的分词器加快速度</p>
</li>
<li><p><strong>禁用评分，延长索引刷新间隔</strong></p>
</li>
<li><p><strong>将多个索引操作放入到batch进行处理</strong></p>
</li>
</ul>
<h3 id="读优化"><a href="#读优化" class="headerlink" title="读优化"></a>读优化</h3><ul>
<li><p>使用<strong>Filter</strong>代替Query，减少打分缓解，使用<strong>bool</strong>组合query和filter查询</p>
</li>
<li><p>对数据进行<strong>分组</strong>，按照日，月，年不同维度分组，查询可集中在局部index中</p>
</li>
</ul>
<h3 id="零停机索引重建方案"><a href="#零停机索引重建方案" class="headerlink" title="零停机索引重建方案"></a>零停机索引重建方案</h3><ul>
<li><p><strong>外部数据导入</strong></p>
<ul>
<li>通过MQ的web控制台或cli命令行，发送指定的MQ消息</li>
<li>MQ消息被微服务模块的消费者消费，触发ES数据重新导入功能</li>
<li>微服务模块从数据库里查询数据的总数及分页信息，并发送至MQ</li>
<li>微服务从MQ中根据分页信息从数据库获取到数据后，根据索引结构的定义，将数据组装成ES支持的JSON格式，并通过bulk命令将数据发送给Elasticsearch集群进行索引的重建工作。</li>
</ul>
</li>
<li><p><strong>基于Scroll+bulk+索引别名的方案</strong></p>
<ul>
<li><p>新建索引book_new，将mapping信息，settings信息等按新的要求全部定义好</p>
</li>
<li><p>使用scroll api将数据批量查询出来，指定scroll查询持续时间</p>
</li>
<li><p>采用bulk api将scoll查出来的一批数据，批量写入新索引</p>
</li>
<li><p>查询一批导入一批，注意每次都使用上次结束时的scoll_id</p>
</li>
<li><p>切换别名book_alias到新的索引book_new上面，此时Java客户端仍然使用别名访问，也不需要修</p>
<p>改任何代码，不需要停机。验证别名查询的是否为新索引的数据</p>
</li>
</ul>
</li>
<li><p><strong>Reindex API方案</strong></p>
<ul>
<li>Elasticsearch v6.3.1已经支持Reindex API，它对scroll、bulk做了一层封装，能够 对文档重建索引而不需要任何插件或外部工具。</li>
</ul>
</li>
</ul>
<p><strong>参与度</strong> &amp; <strong>灵活性</strong>：自研 &gt; scroll+bulk &gt; reindex</p>
<p><strong>稳定性</strong> &amp; <strong>可靠性</strong>：自研 &lt; scroll+bulk &lt; reindex</p>
<h3 id="DeepPaging性能解决方案"><a href="#DeepPaging性能解决方案" class="headerlink" title="DeepPaging性能解决方案"></a>DeepPaging性能解决方案</h3><blockquote>
<p>比如超级管理员，要给某个省份用户发送公告或者广告，最容易想到的就是利用 from + size 来实现，但这是不现实的</p>
</blockquote>
<img src="https://tva1.sinaimg.cn/large/008eGmZEly1gne4vx9hu4j30x60gw0w5.jpg" alt="image-20210206212712493" style="zoom:60%;" />









<h1 id="二：Docker-amp-K8S篇"><a href="#二：Docker-amp-K8S篇" class="headerlink" title="二：Docker&amp;K8S篇"></a>二：Docker&amp;K8S篇</h1><blockquote>
<p>chroot 是在 Unix 和 Linux 系统的一个操作，针对正在运作的软件行程和它的子进程，改变它外显的根目录。一个运行在这个环境下，经由 chroot 设置根目录的程序，它不能够对这个指定根目录之外的文件进行访问动作，不能读取，也不能更改它的内容。</p>
</blockquote>
<p><strong>虚拟化技术_VMware 、VirtualBox、KVM</strong></p>
<p>虚拟化技术就是在操作系统上多加了一个虚拟化层（Hypervisor），可以将物理机的CPU、内存、硬盘、网络等资源进行虚拟化，再通过虚拟化出来的空间上安装操作系统，构建虚拟的应用程序执行环境。这就是我们通常说的虚拟机。</p>
<p>虚拟机的优点：</p>
<ul>
<li>提升IT效率、降低运维成本</li>
<li>更快地部署工作负责</li>
<li>提高服务器可用性</li>
</ul>
<p>虚拟机的缺点：</p>
<ul>
<li>占用资源较多、性能较差</li>
<li>扩展、迁移能力较差</li>
</ul>
<h3 id="Why-Docker"><a href="#Why-Docker" class="headerlink" title="Why Docker"></a>Why Docker</h3><p><strong>场景</strong></p>
<ul>
<li>开发人员在本地编写代码，并使用Docker容器与其他同事共享劳动成果。</li>
<li>使用Docker将应用程序推送到测试环境中，并执行自动和手动测试。</li>
<li>开发人员可以在开发环境中对其进行修复，然后将其重新部署到测试环境中以进行测试和验证。</li>
<li>测试完成后，将修补程序推送给生产环境就像将更新的镜像推送到生产环境一样简单。</li>
</ul>
<p><strong>需求</strong></p>
<blockquote>
<p>快速，一致地交付应用程序、镜像打包环境，避免了环境不一致的问题，简化开发的生命周期，适合于快速迭代敏捷开发的场景</p>
</blockquote>
<img src="https://i.loli.net/2021/02/20/7hx2RcvUPKgXpma.png" alt="image-20210220140837929" style="zoom: 50%;" />



<h3 id="核心概念"><a href="#核心概念" class="headerlink" title="核心概念"></a>核心概念</h3><p><strong>Docker引擎-守护进程</strong></p>
<p>​	Docker使用C &#x2F; S架构 ：用户通过<strong>Docker客户端</strong>与Docker守护进程（Docker引擎）通过Unix套接字或者RESTAPI进行通信，<strong>Docker引擎</strong>完成了构建，运行和分发Docker容器的繁重工作</p>
<p><strong>Docker镜像-Dockerfile</strong></p>
<p>​	Docker镜像类似于虚拟机镜像，是一个只读的模板，是创建Docker容器的基础</p>
<p>​	镜像是基于联合（Union）文件系统的一种层式的结构，由一系列指令一步一步构建出来。</p>
<p>​	比如：拷贝文件、执行命令</p>
<p><strong>Docker仓库-Hub</strong></p>
<p>Docker仓库可以分为<strong>公开仓库 （Public）</strong>和<strong>私有仓库（Private）</strong>两种形式。</p>
<p>最大的公开仓库是官方提供的<strong>Docker Hub</strong>，其中存放了数量庞大的镜像供用户下载。</p>
<h3 id="基本操作"><a href="#基本操作" class="headerlink" title="基本操作"></a>基本操作</h3><p><strong>镜像</strong></p>
<figure class="highlight dockerfile"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line">[root@localhost ~]<span class="comment"># docker pull mysql:5.7.30</span></span><br><span class="line"><span class="number">5.7</span>.<span class="number">30</span>: Pulling <span class="keyword">from</span> library/mysql ……</span><br><span class="line">[root@localhost ~]<span class="comment"># docker images </span></span><br><span class="line">REPOSITORY TAG IMAGE ID CREATED SIZE </span><br><span class="line">mysql <span class="number">5.7</span>.<span class="number">30</span> <span class="number">9</span>cfcce23593a <span class="number">6</span> weeks ago <span class="number">448</span>MB</span><br><span class="line">[root@localhost ~]<span class="comment"># docker tag mysql:5.7.30 mysql5 </span></span><br><span class="line">[root@localhost ~]<span class="comment"># docker images </span></span><br><span class="line">REPOSITORY TAG IMAGE ID CREATED SIZE </span><br><span class="line">mysql5 latest <span class="number">9</span>cfcce23593a <span class="number">6</span> weeks ago <span class="number">448</span>MB </span><br><span class="line">mysql <span class="number">5.7</span>.<span class="number">30</span> <span class="number">9</span>cfcce23593a <span class="number">6</span> weeks ago <span class="number">448</span>MB</span><br><span class="line">[root@localhost ~]<span class="comment"># docker inspect mysql:5.7.30 </span></span><br><span class="line">[&#123;显示docker 详细信息&#125;]</span><br><span class="line">[root@localhost ~]<span class="comment"># docker search mysql</span></span><br><span class="line">[root@localhost ~]<span class="comment"># docker rmi mysql:5.7.30</span></span><br><span class="line">[root@localhost ~]<span class="comment"># docker push mysql[:TAG]</span></span><br></pre></td></tr></table></figure>

<p><strong>容器</strong></p>
<figure class="highlight dockerfile"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line">[root@localhost ~]<span class="comment"># docker create -it nginx</span></span><br><span class="line">[root@localhost ~]<span class="comment"># docker start 9cfcce23593a</span></span><br><span class="line"></span><br><span class="line"><span class="comment">#查看运行的容器 </span></span><br><span class="line">[root@localhost ~]<span class="comment"># docker ps </span></span><br><span class="line"><span class="comment">#查看所有容器 </span></span><br><span class="line">[root@localhost ~]<span class="comment"># docker ps -a</span></span><br><span class="line"><span class="comment">#新建并启动容器</span></span><br><span class="line">[root@localhost ~]<span class="comment"># docker run -it --rm --network host tomcat:8.5.56-jdk8-openjdk</span></span><br></pre></td></tr></table></figure>



<h3 id="实战"><a href="#实战" class="headerlink" title="实战"></a>实战</h3><ol>
<li><p>创建一个卷，待后边使用</p>
<figure class="highlight dockerfile"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">docker <span class="keyword">volume</span><span class="language-bash"> create test_volume</span></span><br></pre></td></tr></table></figure>


</li>
<li><p>分别启动2个容器挂在上卷,</p>
<figure class="highlight dockerfile"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line">在<span class="number">2</span>个终端窗口启动<span class="number">2</span>个容器 </span><br><span class="line">docker <span class="keyword">run</span><span class="language-bash"> -it --<span class="built_in">rm</span> -v test_volume:/test nginx:latest /bin/bash</span></span><br><span class="line">docker <span class="keyword">run</span><span class="language-bash"> -it --<span class="built_in">rm</span> -v test_volume:/test nginx:latest /bin/bash </span></span><br><span class="line">cd /test; </span><br><span class="line">touch a.txt </span><br><span class="line">ls /test <span class="comment"># 在两个容器中我们均可以看到我们创建的文件，shixian在多个容器之间实现数据共享</span></span><br></pre></td></tr></table></figure></li>
</ol>
<p>挂载在容器 &#x2F;test 目录内创建。 Docker <strong>不支持容器内安装点的相对路径</strong>。 多个容器可以在同一时间段内使用相同的卷。如果两个容器需要访问共享数据，例如，如果一个容器写入而另一个容器读取数据。 卷名 在驱动程序test必须唯一。这意味着不能将<strong>相同的卷名</strong>与两个不同的驱动程序一起使用。 如果我们指定了当前test_volume程序上已在使用的卷名，则Docker会假定我们要重用现有卷，并且不会返回错误。如果开始无 test_volume 则会创建这个卷当然除了使用卷，也可以使用将宿主机的文件映射到容器的卷，命令类似，只不过不用提前创建卷，而且数据会映射到宿主机上注意如果宿主机上的目录可以不存在，会在启动容器的时候创建</p>
<h1 id="三、Netty篇"><a href="#三、Netty篇" class="headerlink" title="三、Netty篇"></a>三、Netty篇</h1><h3 id="核心组件"><a href="#核心组件" class="headerlink" title="核心组件"></a>核心组件</h3><h4 id="1、整体结构"><a href="#1、整体结构" class="headerlink" title="1、整体结构"></a>1、整体结构</h4><img src="https://tva1.sinaimg.cn/large/008i3skNly1gq6ijej9w7j30p00doaim.jpg" alt="image-20210504171606057" style="zoom:50%;" />

<p>​	</p>
<p>​	<strong>Core 核心层</strong><br>​	Core 核心层是 Netty 最精华的内容，它提供了底层网络通信的通用抽象和实现，包括事件模型、通用API、支持零拷贝的 ByteBuf 等。</p>
<p>​	<strong>Protocol Support 协议支持层</strong><br>​	协议支持层基本上覆盖了主流协议的编解码实现，如 HTTP、Protobuf、WebSocket、二进制等主流协议，此外 Netty 还支持自定义应用层协议。Netty 丰富的协议支持降低了用户的开发成本，基于 Netty 我们可以快速开发 HTTP、WebSocket 等服务。</p>
<p>​	<strong>Transport Service 传输服务层</strong><br>​	传输服务层提供了网络传输能力的定义和实现方法。它支持 Socket、HTTP 隧道、虚拟机管道等传输方式。Netty 对 TCP、UDP 等数据传输做了抽象和封装，用户可以更聚焦在业务逻辑实现上，而不必关系底层数据传输的细节。</p>
<h4 id="2、逻辑架构"><a href="#2、逻辑架构" class="headerlink" title="2、逻辑架构"></a>2、逻辑架构</h4><img src="https://tva1.sinaimg.cn/large/008i3skNly1gq6iiju6h8j30ry0o6dj0.jpg" alt="image-20210504171514089" style="zoom:50%;" />

<p>​		</p>
<p>​	<strong>网络通信层</strong><br>​	网络通信层的职责是执行网络 I&#x2F;O 的操作。它支持多种网络协议和 I&#x2F;O 模型的连接操作。当网络数据读取到内核缓冲区后，会触发各种网络事件，这些网络事件会分发给事件调度层进行处理。</p>
<p>网络通信层的核心组件包含<strong>BootStrap、ServerBootStrap、Channel</strong>三个组件。</p>
<p>​	Bootstrap 是“引导”的意思，负责 Netty <strong>客户端程序</strong>的启动、初始化、服务器连接等过程，串联了 Netty 的其他核心组件。</p>
<p>​	ServerBootStrap 用于<strong>服务端启动</strong>绑定本地端口，会绑定Boss 和 Worker两个 EventLoopGroup。</p>
<p>​	Channel 的是“<strong>通道</strong>”，Netty Channel提供了基于NIO更高层次的抽象，如 register、bind、connect、read、write、flush 等。</p>
<p>​	</p>
<p>​	<strong>事件调度层</strong><br>​	事件调度层的职责是通过 Reactor 线程模型对各类事件进行聚合处理，通过 Selector 主循环线程集成多种事件（ I&#x2F;O 事件、信号事件、定时事件等），实际的业务处理逻辑是交由服务编排层中相关的 Handler 完成。</p>
<p>事件调度层的核心组件包括 <strong>EventLoopGroup、EventLoop</strong>。</p>
<img src="https://tva1.sinaimg.cn/large/008i3skNly1gq6ijuqesxj30ke0ekgpj.jpg" alt="image-20210504171631793" style="zoom:50%;" />

<p>​						</p>
<p>​	<strong>EventLoop</strong> 负责处理 Channel 生命周期内的所有 I&#x2F;O 事件，如 accept、connect、read、write 等 I&#x2F;O 事件</p>
<p>​		①一个 EventLoopGroup 往往包含<strong>一个或者多个</strong> EventLoop。</p>
<p>​		②EventLoop 同一时间会与一个Channel绑定，每个 EventLoop 负责<strong>处理一种类型 Channel</strong>。</p>
<p>​		③Channel 在生命周期内可以对和多个 EventLoop 进行<strong>多次绑定和解绑</strong>。		</p>
<p>​	<strong>EventLoopGroup</strong> 是Netty 的<strong>核心处理引擎</strong>，本质是一个线程池，主要负责接收 I&#x2F;O 请求，并分配线程执行处理请求。通过创建不同的 EventLoopGroup 参数配置，就可以支持 Reactor 的三种线程模型：</p>
<p>​		<strong>单线程模型</strong>：EventLoopGroup 只包含一个 EventLoop，Boss 和 Worker 使用同一个EventLoopGroup；</p>
<p>​		<strong>多线程模型</strong>：EventLoopGroup 包含多个 EventLoop，Boss 和 Worker 使用同一个EventLoopGroup；</p>
<p>​		<strong>主从多线程模型</strong>：EventLoopGroup 包含多个 EventLoop，Boss 是主 Reactor，Worker 是从 Reactor，它们分别使用不同的 EventLoopGroup，主 Reactor 负责新的网络连接 Channel 创建，然后把 Channel 注册到从 Reactor。</p>
<p>​	<strong>服务编排层</strong><br>​	服务编排层的职责是负责组装各类服务，它是 Netty 的核心处理链，用以实现网络事件的动态编排和有序传播。</p>
<p>服务编排层的核心组件包括 <strong>ChannelPipeline、ChannelHandler、ChannelHandlerContext</strong>。</p>
<p>​	<strong>ChannelPipeline</strong> 是 Netty 的核心编排组件，负责组装各种 ChannelHandler，ChannelPipeline 内部通过双向链表将不同的 ChannelHandler 链接在一起。当 I&#x2F;O 读写事件触发时，Pipeline 会依次调用 Handler 列表对 Channel 的数据进行拦截和处理。</p>
<img src="https://tva1.sinaimg.cn/large/008i3skNly1gq6il759apj313s068abj.jpg" alt="image-20210504171749533" style="zoom:50%;" />

<p>​	</p>
<p>​	客户端和服务端都有各自的 ChannelPipeline。客户端和服务端一次完整的请求：客户端出站（Encoder 请求数据）、服务端入站（Decoder接收数据并执行业务逻辑）、服务端出站（Encoder响应结果）。</p>
<p>​	<strong>ChannelHandler</strong> 完成数据的编解码以及处理工作。</p>
<img src="https://tva1.sinaimg.cn/large/008i3skNly1gq6ilvuhupj30ye08e0vd.jpg" alt="image-20210504171829071" style="zoom:50%;" />



<p>​	<strong>ChannelHandlerContext</strong> 用于保存Handler 上下文，通过 HandlerContext 我们可以知道 Pipeline 和 Handler 的关联关系。HandlerContext 可以实现 Handler 之间的交互，HandlerContext 包含了 Handler 生命周期的所有事件，如 connect、bind、read、flush、write、close 等。同时，HandlerContext 实现了Handler通用的逻辑的模型抽象。</p>
<img src="https://tva1.sinaimg.cn/large/008i3skNly1gq6imu2khlj31080gu0xc.jpg" alt="image-20210504171924019" style="zoom:50%;" />





<h3 id="网络传输"><a href="#网络传输" class="headerlink" title="网络传输"></a>网络传输</h3><h4 id="1、五种IO模型的区别"><a href="#1、五种IO模型的区别" class="headerlink" title="1、五种IO模型的区别"></a><strong>1、五种IO模型的区别</strong></h4><p><strong>阻塞I&#x2F;O：（BIO）</strong></p>
<img src="https://tva1.sinaimg.cn/large/008i3skNly1gq6ingki0yj30kw0d6gmr.jpg" alt="image-20210504171959821" style="zoom:50%;" />

<p>​	</p>
<p>​		应用进程向内核发起 I&#x2F;O 请求，发起调用的线程一直等待内核返回结果。一次完整的 I&#x2F;O 请求称为BIO（Blocking IO，阻塞 I&#x2F;O），所以 BIO 在实现异步操作时，只能使用多线程模型，一个请求对应一个线程。但是，<strong>线程的资源是有限且宝贵的，创建过多的线程会增加线程切换的开销。</strong></p>
<p><strong>同步非阻塞I&#x2F;O（NIO）：</strong></p>
<img src="https://tva1.sinaimg.cn/large/008i3skNly1gq6inzsk9xj30lg0cign1.jpg" alt="image-20210504172029418" style="zoom:50%;" />

<p>​		</p>
<p>​		应用进程向内核发起 I&#x2F;O 请求后不再会同步等待结果，而是会立即返回，通过轮询的方式获取请求结果。NIO 相比 BIO 虽然大幅提升了性能，但是轮询过程中大量的系统调用导致上下文切换开销很大。所以，单独使用非阻塞 I&#x2F;O 时效率并不高，而且<strong>随着并发量的提升，非阻塞 I&#x2F;O 会存在严重的性能浪费。</strong></p>
<p><strong>多路复用I&#x2F;O（select和poll）：</strong></p>
<img src="https://tva1.sinaimg.cn/large/008i3skNly1gq6iogl9x0j30ja0cqdh7.jpg" alt="image-20210504172057237" style="zoom:50%;" />

<p>​		</p>
<p>​		多路复用实现了<strong>一个线程处理多个 I&#x2F;O 句柄的操作</strong>。多路指的是多个数据通道，复用指的是使用一个或多个固定线程来处理每一个 Socket。select、poll、epoll 都是 I&#x2F;O 多路复用的具体实现，线程一次 select 调用可以获取内核态中多个数据通道的数据状态。其中，select只负责等，recvfrom只负责拷贝，阻塞IO中可以对多个文件描述符进行阻塞监听，是一种非常高效的 I&#x2F;O 模型。</p>
<p><strong>信号驱动I&#x2F;O（SIGIO）：</strong></p>
<img src="https://tva1.sinaimg.cn/large/008i3skNly1gq6ioxthajj30ii0cemyk.jpg" alt="image-20210504172124965" style="zoom:50%;" />

<p>​		</p>
<p>​		信号驱动IO模型，应用进程告诉内核：当数据报准备好的时候，给我发送一个信号，对SIGIO信号进行捕捉，并且调用我的信号处理函数来获取数据报。</p>
<p><strong>异步I&#x2F;O（Posix.1的aio_系列函数）：</strong></p>
<p>​		<img src="https://tva1.sinaimg.cn/large/008i3skNly1gq6ipcc12jj30lg0coabe.jpg" alt="image-20210504172148095" style="zoom:50%;" /></p>
<p>​		当应用程序调用aio_read时，内核一方面去取数据报内容返回，另一方面将程序控制权还给应用进程，应用进程继续处理其他事情，是一种非阻塞的状态。当内核中有数据报就绪时，由内核将数据报拷贝到应用程序中，返回aio_read中定义好的函数处理程序。</p>
<h4 id="2、Reactor多线程模型"><a href="#2、Reactor多线程模型" class="headerlink" title="2、Reactor多线程模型"></a>2、Reactor多线程模型</h4><p>​		Netty 的 I&#x2F;O 模型是基于<strong>非阻塞 I&#x2F;O</strong> 实现的，底层依赖的是 NIO 框架的<strong>多路复用器 Selector</strong>。采用 <strong>epoll 模式</strong>后，只需要一个线程负责 Selector 的轮询。当有数据处于就绪状态后，需要一个<strong>事件分发器</strong>（Event Dispather），它负责将读写事件分发给对应的读写<strong>事件处理器</strong>（Event Handler）。事件分发器有两种设计模式：<strong>Reactor 和 Proactor</strong>，Reactor 采用同步 I&#x2F;O， Proactor 采用异步 I&#x2F;O。</p>
<p>​	</p>
<img src="https://tva1.sinaimg.cn/large/008i3skNly1gq6ipob6wjj30we0i4jz2.jpg" alt="image-20210504172207142" style="zoom:50%;" />



<p>​		Reactor 实现相对简单，适合处理耗时短的场景，对于耗时长的 I&#x2F;O 操作容易造成阻塞。Proactor 性能更高，但是实现逻辑非常复杂，适合图片或视频流分析服务器，目前主流的事件驱动模型还是依赖 <strong>select 或 epoll</strong> 来实现。</p>
<h4 id="3、拆包粘包问题"><a href="#3、拆包粘包问题" class="headerlink" title="3、拆包粘包问题"></a>3、拆包粘包问题</h4><p><strong>拆包</strong>TCP 传输协议是面向流的，没有数据包界限。<br><strong>MTU（Maxitum Transmission Unit）</strong> 是链路层一次最大传输数据的大小。MTU 一般来说大小为 1500 byte。<strong>MSS（Maximum Segement Size）</strong> 是指 TCP 最大报文段长度，它是传输层一次发送最大数据的大小。</p>
<img src="https://tva1.sinaimg.cn/large/008i3skNly1gq6iq4xdjtj30q407egnk.jpg" alt="image-20210504172233844" style="zoom:50%;" />	

<p>如上图所示，如果 MSS + TCP 首部 + IP 首部 &gt; MTU，那么数据包将会被拆分为多个发送。这就是<strong>拆包现象</strong>。</p>
<p><strong>Nagle 算法</strong><br>Nagle 算法可以理解为批量发送，也是我们平时编程中经常用到的优化思路，它是在数据未得到确认之前先写入缓冲区，等待数据确认或者缓冲区积攒到一定大小再把数据包发送出去。Netty 中为了使数据<strong>传输延迟最小化</strong>，就默认<strong>禁用了 Nagle 算法</strong>。</p>
<p><strong>拆包&#x2F;粘包的解决方案</strong></p>
<p>在客户端和服务端通信的过程中，服务端一次读到的数据大小是不确定的。需要确定边界：</p>
<p><strong>消息长度固定</strong><br><strong>特定分隔符</strong><br><strong>消息长度 + 消息内容</strong>(Netty)</p>
<h4 id="4、自定义协议"><a href="#4、自定义协议" class="headerlink" title="4、自定义协议"></a>4、自定义协议</h4><p>Netty 常用编码器类型：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">MessageToByteEncoder <span class="comment">//对象编码成字节流；</span></span><br><span class="line"></span><br><span class="line">MessageToMessageEncoder <span class="comment">//一种消息类型编码成另外一种消息类型。</span></span><br></pre></td></tr></table></figure>

<p>Netty 常用解码器类型：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">ByteToMessageDecoder/ReplayingDecoder <span class="comment">//将字节流解码为消息对象；</span></span><br><span class="line"></span><br><span class="line">MessageToMessageDecoder <span class="comment">//将一种消息类型解码为另外一种消息类型。</span></span><br></pre></td></tr></table></figure>

<p>编解码器可以分为<strong>一次解码器</strong>和<strong>二次解码器</strong>，一次解码器用于解决 <strong>TCP 拆包&#x2F;粘包问题</strong>，按协议解析后得到的字节数据。如果你需要对解析后的<strong>字节数据做对象模型</strong>的转换，这时候便需要用到二次解码器，同理编码器的过程是反过来的。</p>
<p><strong>Netty自定义协议内容：</strong></p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/*</span></span><br><span class="line"><span class="comment">+---------------------------------------------------------------+</span></span><br><span class="line"><span class="comment">| 魔数 2byte | 协议版本号 1byte | 序列化算法 1byte | 报文类型 1byte  |</span></span><br><span class="line"><span class="comment">+---------------------------------------------------------------+</span></span><br><span class="line"><span class="comment">| 状态 1byte |        保留字段 4byte     |      数据长度 4byte     | </span></span><br><span class="line"><span class="comment">+---------------------------------------------------------------+</span></span><br><span class="line"><span class="comment">|                   数据内容 （长度不定）                          |</span></span><br><span class="line"><span class="comment">+---------------------------------------------------------------+</span></span><br><span class="line"><span class="comment"> */</span></span><br></pre></td></tr></table></figure>

<p>如何判断 ByteBuf 是否存在完整的报文？最常用的做法就是通过读取消息长度 dataLength 进行判断。如果 ByteBuf 的可读数据长度小于 dataLength，说明 ByteBuf 还不够获取一个完整的报文。</p>
<h4 id="5、WriteAndFlush"><a href="#5、WriteAndFlush" class="headerlink" title="5、WriteAndFlush"></a>5、WriteAndFlush</h4><p>​		<img src="https://tva1.sinaimg.cn/large/008i3skNly1gq6iqnas8fj31400lkaj2.jpg" alt="image-20210504172303465" style="zoom:50%;" /></p>
<p>​	①writeAndFlush 属于出站操作，它是从 Pipeline 的 Tail 节点开始进行事件传播，一直向前传播到 Head 节点。不管在 write 还是 flush 过程，Head 节点都中扮演着重要的角色。</p>
<p>​	②write 方法并没有将数据写入 Socket 缓冲区，只是将数据写入到 ChannelOutboundBuffer 缓存中，ChannelOutboundBuffer 缓存内部是由单向链表实现的。</p>
<p>​	③flush 方法才最终将数据写入到 Socket 缓冲区。</p>
<h3 id="内存管理"><a href="#内存管理" class="headerlink" title="内存管理"></a>内存管理</h3><h4 id="1、堆外内存"><a href="#1、堆外内存" class="headerlink" title="1、堆外内存"></a>1、堆外内存</h4><p>​	在 Java 中对象都是在堆内分配的，通常我们说的<strong>JVM 内存</strong>也就指的<strong>堆内内存</strong>，<strong>堆内内存</strong>完全被<strong>JVM 虚拟机</strong>所管理，JVM 有自己的垃圾回收算法，对于使用者来说不必关心对象的内存如何回收。<strong>堆外内存</strong>与堆内内存相对应，对于整个机器内存而言，除<strong>堆内内存以外部分即为堆外内存</strong>。堆外内存不受 JVM 虚拟机管理，直接由操作系统管理。使用堆外内存有如下几个优点：</p>
<ol>
<li>堆内内存由 JVM GC 自动回收内存，降低了 Java 用户的使用心智，堆外内存由于不受 JVM 管理，所以在一定程度上可以降低 GC 对应用运行时带来的影响。</li>
<li>堆外内存需要手动释放，这一点跟 C&#x2F;C++ 很像，稍有不慎就会造成应用程序内存泄漏，当出现内存泄漏问题时排查起来会相对困难。</li>
<li>当进行网络 I&#x2F;O 操作、文件读写时，堆内内存都需要转换为堆外内存，然后再与底层设备进行交互，所以直接使用堆外内存可以减少一次内存拷贝。</li>
<li>堆外内存可以方便实现进程之间、JVM 多实例之间的数据共享。</li>
</ol>
<p>​    在堆内存放的 DirectByteBuffer 对象并不大，仅仅包含堆外内存的地址、大小等属性，同时还会创建对应的 Cleaner 对象，通过 ByteBuffer 分配的堆外内存不需要手动回收，它可以被 JVM 自动回收。当堆内的 DirectByteBuffer 对象被 GC 回收时，Cleaner 就会用于回收对应的堆外内存。</p>
<img src="https://tva1.sinaimg.cn/large/008i3skNly1gq6ir0d0cmj30qw0hw41z.jpg" alt="image-20210504172324820" style="zoom:50%;" />

<p>​	从 DirectByteBuffer 的构造函数中可以看出，真正分配堆外内存的逻辑还是通过 unsafe.allocateMemory(size)，Unsafe 是一个非常不安全的类，它用于执行内存访问、分配、修改等<strong>敏感操作</strong>，可以越过 JVM 限制的枷锁。Unsafe 最初并不是为开发者设计的，使用它时虽然可以获取对底层资源的控制权，但也失去了安全性的保证，使用 Unsafe 一定要慎重（Java 中是不能直接使用 Unsafe 的，但是可以通过反射获取 Unsafe 实例）。Netty 中依赖了 Unsafe 工具类，是因为 Netty 需要与底层 Socket 进行交互，Unsafe 提升 Netty 的性能</p>
<p>​	 因为DirectByteBuffer 对象的回收需要依赖 Old GC 或者 Full GC 才能触发清理，如果长时间没有 GC执行，那么堆外内存即使不再使用，也会一直在占用内存不释放，很容易将机器的物理内存耗尽。-XX:MaxDirectMemorySize 指定堆外内存的上限大小，超出时触发GC，仍无法释放抛出OOM异常。</p>
<img src="https://tva1.sinaimg.cn/large/008i3skNly1gq6ir0d0cmj30qw0hw41z.jpg" alt="image-20210504172324820" style="zoom:50%;" />

<p>​	当初始化堆外内存时，内存中的对象引用情况如下图所示，first 是 Cleaner 类中的静态变量，Cleaner 对象在初始化时会加入 Cleaner 链表中。DirectByteBuffer 对象包含堆外内存的地址、大小以及 Cleaner 对象的引用，ReferenceQueue 用于保存需要回收的 Cleaner 对象。</p>
<p>​	</p>
<h4 id="2、数据载体ByteBuf"><a href="#2、数据载体ByteBuf" class="headerlink" title="2、数据载体ByteBuf"></a>2、<strong>数据载体ByteBuf</strong></h4><p>JDK NIO 的 <strong>ByteBuffer</strong></p>
<ul>
<li>mark：为某个读取过的关键位置做标记，方便回退到该位置；</li>
<li>position：当前读取的位置；</li>
<li>limit：buffer 中有效的数据长度大小；</li>
<li>capacity：初始化时的空间容量。</li>
</ul>
<img src="https://tva1.sinaimg.cn/large/008i3skNly1gq6irlptv0j30z408wabn.jpg" alt="image-20210504172358702" style="zoom:50%;" />

<p>​	第一，ByteBuffer 分配的长度是固定的，无法动态扩缩容，每次在存放数据的时候对容量大小做校验，扩容需要将已有的数据迁移。</p>
<p>​	第二，ByteBuffer 只能通过 position 获取当前可操作的位置，因为读写共用的 position 指针，所以需要频繁调用 flip、rewind 方法切换读写状态。</p>
<p>Netty中的ByteBuf</p>
<ul>
<li><strong>废弃字节</strong>，表示已经丢弃的无效字节数据。</li>
<li><strong>可读字节</strong>，表示 ByteBuf 中可以被读取的字节内容，可以通过 writeIndex - readerIndex 计算得出。当读写位置重叠时时，表示 ByteBuf 已经不可读。</li>
<li><strong>可写字节</strong>，向 ByteBuf 中写入数据都会存储到可写字节区域。当 writeIndex 超过 capacity，表示 ByteBuf 容量不足，需要扩容。</li>
<li><strong>可扩容字节</strong>，表示 ByteBuf 最多还可以扩容多少字节，最多扩容到 maxCapacity 为止，超过 maxCapacity 再写入就会出错。</li>
</ul>
<img src="https://tva1.sinaimg.cn/large/008i3skNly1gq6j1t85zuj31020ds42m.jpg" alt="image-20210504173347000" style="zoom:50%;" />

<p><strong>引用计数</strong></p>
<p>​	当byteBuf当引用计数为 0，该 ByteBuf 可以被放入到对象池中，避免每次使用 ByteBuf 都重复创建。</p>
<p>​	JVM 并不知道 Netty 的引用计数是如何实现的，当 ByteBuf 对象不可达时，一样会被 GC 回收掉，但是如果此时 ByteBuf 的引用计数不为 0，那么该对象就不会释放或者被放入对象池，从而发生了内存泄漏。Netty 会对分配的 ByteBuf 进行抽样分析，检测 ByteBuf 是否已经不可达且引用计数大于 0，判定内存泄漏的位置并输出到日志中，<strong>通过关注日志中 LEAK 关键字可以找到内存泄漏的具体对象</strong>。</p>
<h4 id="3、内存分配jemalloc"><a href="#3、内存分配jemalloc" class="headerlink" title="3、内存分配jemalloc"></a>3、<strong>内存分配jemalloc</strong></h4><p>​	为了减少分配时产生的内部碎片和外部碎片，常见的内存分配算法<strong>动态内存分配</strong>、<strong>伙伴算法</strong>和<strong>Slab 算法</strong></p>
<p><strong>动态内存分配（DMA）</strong></p>
<p>​	<strong>⾸次适应算法（first fit）</strong>，空闲分区链以地址递增的顺序将空闲分区以双向链表的形式连接在一起，从空闲分区链中找到第一个满足分配条件的空闲分区，然后从空闲分区中划分出一块可用内存给请求进程，剩余的空闲分区仍然保留在空闲分区链中。</p>
<img src="https://tva1.sinaimg.cn/large/008i3skNly1gq6j26fh88j30ni0ea41c.jpg" alt="image-20210504173407923" style="zoom:50%;" />

<p>​	<strong>循环首次适应算法（next fit）</strong>不再是每次从链表的开始进行查找，而是从上次找到的空闲分区的以后开始查找。查找效率提升，会产生更多的碎片。</p>
<p>​	<strong>最佳适应算法（best fit）</strong>，空闲分区链以空闲分区大小递增的顺序将空闲分区以双向链表的形式连接在一起，每次从空闲分区链的开头进行查找。</p>
<p><strong>伙伴算法</strong>（外部碎片少，内部碎片多）</p>
<p>​	是一种非常经典的内存分配算法，它采用了<strong>分离适配的设计思想</strong>，将物理内存按照 2 的次幂进行划分，内存分配时也是按照 2 的次幂大小进行按需分配</p>
<img src="https://tva1.sinaimg.cn/large/008i3skNly1gq6j2m0rr1j30ly0iugnk.jpg" alt="image-20210504173433749" style="zoom:50%;" />

<ol>
<li>首先需要找到存储 2^4 连续 Page 所对应的链表，即数组下标为 4；</li>
<li>查找 2^4 链表中是否有空闲的内存块，如果有则分配成功；</li>
<li>如果 2^4 链表不存在空闲的内存块，则继续沿数组向上查找，即定位到数组下标为 5 的链表，链表中每个节点存储 2^5 的连续 Page；</li>
<li>如果 2^5 链表中存在空闲的内存块，则取出该内存块并将它分割为 2 个 2^4 大小的内存块，其中一块分配给进程使用，剩余的一块链接到 2^4 链表中。</li>
</ol>
<p><strong>Slab 算法（解决伙伴算法内部碎片问题）</strong></p>
<p>​	Slab 算法在伙伴算法的基础上，对小内存的场景专门做了优化，采用了内存池的方案，解决内部碎片问题。</p>
<img src="https://tva1.sinaimg.cn/large/008i3skNly1gq6j3160yuj30rw0eo77o.jpg" alt="image-20210504173454562" style="zoom:50%;" />

<p>在 Slab 算法中维护着大小不同的 Slab 集合，将这块内存划分为大小相同的 slot，不会对内存块再进行合并，同时使用位图 bitmap 记录每个 slot 的使用情况。</p>
<p>​	kmem_cache 中包含三个 Slab 链表：<strong>完全分配使用 slab_full</strong>、<strong>部分分配使用 slab_partial</strong>和<strong>完全空闲 slabs_empty</strong>，这三个链表负责内存的分配和释放。Slab 算法是基于对象进行内存管理的，它把相同类型的对象分为一类。当分配内存时，从 Slab 链表中划分相应的内存单元；单个 Slab 可以在不同的链表之间移动，例如当一个 Slab 被分配完，就会从 slab_partial 移动到 slabs_full，当一个 Slab 中有对象被释放后，就会从 slab_full 再次回到 slab_partial，所有对象都被释放完的话，就会从 slab_partial 移动到 slab_empty。当<strong>释放内存时，Slab 算法并不会丢弃已经分配的对象，而是将它保存在缓存中，当下次再为对象分配内存时，直接会使用最近释放的内存块</strong>。</p>
<h4 id="4、jemalloc-架构"><a href="#4、jemalloc-架构" class="headerlink" title="4、jemalloc 架构"></a>4、jemalloc 架构</h4><ul>
<li>内存是由一定数量的 arenas 负责管理，线程均匀分布在 arenas 当中；</li>
<li>每个 arena 都包含一个 bin 数组，每个 bin 管理不同档位的内存块；</li>
<li>每个 arena 被划分为若干个 chunks，每个 chunk 又包含若干个 runs，每个 run 由连续的 Page 组成，run 才是实际分配内存的操作对象；</li>
<li>每个 run 会被划分为一定数量的 regions，在小内存的分配场景，region 相当于用户内存；</li>
<li>每个 tcache 对应一个 arena，tcache 中包含多种类型的 bin。</li>
</ul>
<img src="https://tva1.sinaimg.cn/large/008i3skNly1gq6j3160yuj30rw0eo77o.jpg" alt="image-20210504173454562" style="zoom:50%;" />

<p><strong>内存管理Arena</strong> ，内存由一定数量的 arenas 负责管理。每个用户线程采用 round-robin 轮询的方式选择可用的 arena 进行内存分配。</p>
<p><strong>分级管理Bin</strong>，每个 bin 管理的内存大小是按分类依次递增。<strong>jemalloc 中小内存的分配是基于 Slab 算法</strong>完成的，会产生不同类别的内存块。</p>
<p><strong>Page集合chunk</strong>，chunk 以 Page 为单位管理内存。每个 chunk 可被用于多次小内存的申请，但是在大内存分配的场景下只能分配一次。</p>
<p><strong>实际分配单位run</strong>，run 结构具体的大小由不同的 bin 决定，例如 8 字节的 bin 对应的 run 只有一个 Page，可以从中选取 8 字节的块进行分配。</p>
<p><strong>run 细分region</strong>，每个 run 会将划分为若干个等长的 region，每次内存分配也是按照 region 进行分发。</p>
<p><strong>tcache 是每个线程私有的缓存</strong>，tcache 每次从 arena 申请一批内存，在分配内存时首先在 tcache 查找，避免锁竞争，分配失败才会通过 run 执行内存分配。</p>
<p><img src="https://tva1.sinaimg.cn/large/008i3skNly1gx2u1jn9b3j31e80hqjt5.jpg" alt="image-20211205121406792"></p>
<p>Small 场景，如果请求分配内存的大小小于 arena 中的最小的 bin，那么优先从线程中对应的 tcache 中进行分配。首先确定查找对应的 tbin 中是否存在缓存的内存块，如果存在则分配成功，否则找到 tbin 对应的 arena，从 arena 中对应的 bin 中分配 region 保存在 tbin 的 avail 数组中，最终从 availl 数组中选取一个地址进行内存分配，当内存释放时也会将被回收的内存块进行缓存。</p>
<p>Large 场景的内存分配与 Smalll 类似，如果请求分配内存的大小大于 arena 中的最小的 bin，但是不大于 tcache 中能够缓存的最大块，依然会通过 tcache 进行分配，但是不同的是此时会分配 chunk 以及所对应的 run，从 chunk 中找到相应的内存空间进行分配。内存释放时也跟 samll 场景类似，会把释放的内存块缓存在 tacache 的 tbin 中。此外还有一种情况，当请求分配内存的大小大于tcache 中能够缓存的最大块，但是不大于 chunk 的大小，那么将不会采用 tcache 机制，直接在 chunk 中进行内存分配。</p>
<p>Huge 场景，如果请求分配内存的大小大于 chunk 的大小，那么直接通过 mmap 进行分配，调用 munmap 进行回收。</p>
<h4 id="5、内存池设计（待补充）"><a href="#5、内存池设计（待补充）" class="headerlink" title="5、内存池设计（待补充）"></a>5、内存池设计（待补充）</h4><h4 id="6、Recycle对象池（待补充）"><a href="#6、Recycle对象池（待补充）" class="headerlink" title="6、Recycle对象池（待补充）"></a>6、Recycle对象池（待补充）</h4><h4 id="7、零拷贝技术"><a href="#7、零拷贝技术" class="headerlink" title="7、零拷贝技术"></a>7、零拷贝技术</h4><ol>
<li>当用户进程发起 read() 调用后，上下文从用户态切换至内核态。DMA 引擎从文件中读取数据，并存储到内核态缓冲区，这里是<strong>第一次数据拷贝</strong>。</li>
<li>请求的数据从内核态缓冲区拷贝到用户态缓冲区，然后返回给用户进程。<strong>第二次数据拷贝</strong>的过程同时，会导致上下文从内核态再次切换到用户态。</li>
<li>用户进程调用 send() 方法期望将数据发送到网络中，用户态会再次切换到内核态，<strong>第三次数据拷贝</strong>请求的数据从用户态缓冲区被拷贝到 Socket 缓冲区。</li>
<li>最终 send() 系统调用结束返回给用户进程，发生了第四次上下文切换。<strong>第四次拷贝会异步执行</strong>，从 Socket 缓冲区拷贝到协议引擎中。</li>
</ol>
<img src="https://tva1.sinaimg.cn/large/008i3skNly1gq6jlghxe0j30t00fsjtw.jpg" alt="image-20210504175240348" style="zoom:50%;" />

<p>​	<strong>在 Linux 中</strong>系统调用 sendfile() 可以实现将数据从一个文件描述符传输到另一个文件描述符，从而实现了零拷贝技术。</p>
<p>​	<strong>在 Java 中</strong>也使用了零拷贝技术，它就是 NIO FileChannel 类中的 transferTo() 方法，它可以将数据从 FileChannel 直接传输到另外一个 Channel。</p>
<img src="https://tva1.sinaimg.cn/large/008i3skNly1gq6jm8q3yej311c0h6q7v.jpg" alt="image-20210504175323875" style="zoom:50%;" />

<p><strong>Netty 中的零拷贝</strong>技术除了操作系统级别的功能封装，更多的是面向用户态的数据操作优化，主要体现在以下 5 个方面：</p>
<ul>
<li>堆外内存，避免 JVM 堆内存到堆外内存的数据拷贝。</li>
<li>CompositeByteBuf 类，可以组合多个 Buffer 对象合并成一个逻辑上的对象，避免通过传统内存拷贝的方式将几个 Buffer 合并成一个大的 Buffer。</li>
<li>通过 Unpooled.wrappedBuffer 可以将 byte 数组包装成 ByteBuf 对象，包装过程中不会产生内存拷贝。</li>
<li>ByteBuf.slice ，slice 操作可以将一个 ByteBuf 对象切分成多个 ByteBuf 对象，切分过程中不会产生内存拷贝，底层共享一个 byte 数组的存储空间。</li>
<li>Netty 使用 封装了transferTo() 方法 FileRegion，可以将文件缓冲区的数据直接传输到目标 Channel，避免内核缓冲区和用户态缓冲区之间的数据拷贝。</li>
</ul>
<h3 id="高性能数据结构"><a href="#高性能数据结构" class="headerlink" title="高性能数据结构"></a>高性能数据结构</h3><h4 id="1、FastThreadLocal"><a href="#1、FastThreadLocal" class="headerlink" title="1、FastThreadLocal"></a>1、FastThreadLocal</h4><p>​	ThreadLocal 可以理解为线程本地变量。ThreadLocal 为变量在每个线程中都创建了一个副本，该副本只能被当前线程访问，多线程之间是隔离的，变量不能在多线程之间共享。这样每个线程修改变量副本时，不会对其他线程产生影响。</p>
<p>​	既然多线程访问 ThreadLocal 变量时都会有自己独立的实例副本，那么很容易想到的方案就是在 ThreadLocal 中维护一个 Map，记录线程与实例之间的映射关系。当新增线程和销毁线程时都需要更新 Map 中的映射关系，因为会存在多线程并发修改，所以需要保证 Map 是线程安全的。但是在高并发的场景并发修改 Map 需要加锁，势必会降低性能。</p>
<img src="https://tva1.sinaimg.cn/large/008i3skNly1gq6jmqtl1hj30q60dmtck.jpg" alt="image-20210504175349901" style="zoom:50%;" />

<p>​	JDK 为了避免加锁，采用了相反的设计思路。以 Thread 入手，在 Thread 中维护一个 Map，记录 ThreadLocal 与实例之间的映射关系，这样在同一个线程内，Map 就不需要加锁了。</p>
<img src="https://tva1.sinaimg.cn/large/008i3skNly1gq6jmyxnylj30ns06adgu.jpg" alt="image-20210504175406824" style="zoom:50%;" />

<p>​	ThreadLocalMap 是一种使用线性探测法实现的哈希表，底层采用数组存储数据，通过魔数0x61c88647来使散列更加平衡。ThreadLocalMap 初始化一个长度为 16 的 Entry 数组。与 HashMap 不同的是，Entry 的 key 就是 ThreadLocal对象本身，value 就是用户具体需要存储的值。</p>
<img src="https://tva1.sinaimg.cn/large/008i3skNly1gq6jncecy1j30yy0eejtq.jpg" alt="image-20210504175428964" style="zoom:50%;" />

<p>​	Entry 继承自弱引用类 WeakReference，Entry 的 key 是弱引用，value 是强引用。在 JVM 垃圾回收时，只要发现了弱引用的对象，不管内存是否充足，都会被回收。那么为什么 Entry 的 key 要设计成弱引用呢？如果 key 都是强引用，当线 ThreadLocal 不再使用时，然而 ThreadLocalMap 中还是存在对 ThreadLocal 的强引用，那么 GC 是无法回收的，从而造成内存泄漏。</p>
<img src="https://tva1.sinaimg.cn/large/0081Kckwly1gm4umi0759j30hi0a03zd.jpg" alt="img" style="zoom: 67%;" />

<p>​	虽然 Entry 的 key 设计成了弱引用，但是当 ThreadLocal不再使用(<strong>业务逻辑走完，但是由于线程复用导致线程并没有结束</strong>)被 GC 回收后，ThreadLocalMap 中可能出现 Entry 的 key 为 NULL，那么 Entry 的 value 一直会强引用数据而得不到释放，只能等待线程销毁。那么应该如何避免 ThreadLocalMap 内存泄漏呢？ThreadLocal 已经帮助我们做了一定的保护措施，在执行 ThreadLocal.set()&#x2F;get() 方法时，ThreadLocal 会清除 ThreadLocalMap 中 key 为 NULL 的 Entry 对象，让它还能够被 GC 回收。除此之外，当线程中某个 ThreadLocal 对象不再使用时，立即调用 remove() 方法删除 Entry 对象。如果是在异常的场景中，应在 finally 代码块中进行清理，保持良好的编码意识。在Netty中，可以方便的使用FashThreadLocal来防止内存泄漏</p>
<img src="https://tva1.sinaimg.cn/large/0081Kckwly1gm4ux5gohpj30hs0ajjs1.jpg" alt="img" style="zoom:67%;" />

<p><strong>FastThreadLocal</strong></p>
<p>​	FastThreadLocal 使用 Object 数组替代了 Entry 数组，Object[0] 存储的是一个Set&lt;FastThreadLocal&lt;?&gt;&gt; 集合，从数组下标 1 开始都是直接存储的 value 数据，不再采用 ThreadLocal 的键值对形式进行存储。主要是针对set方法，增加了两个额外的行为。</p>
<ol>
<li>找到数组下标 index 位置，设置新的 value。</li>
<li>将 <strong>FastThreadLocal 对象保存到待清理的 Set 中</strong>。</li>
</ol>
<img src="https://tva1.sinaimg.cn/large/008i3skNly1gq6jnu8l6aj315k060wfi.jpg" alt="image-20210504175457264" style="zoom:50%;" />

<ul>
<li><strong>高效查找</strong>。FastThreadLocal 在定位数据的时候可以直接根据数组下标 index 获取，时间复杂度 O(1)。而 JDK 原生的 ThreadLocal 在数据较多时哈希表很容易发生 Hash 冲突，线性探测法在解决 Hash 冲突时需要不停地向下寻找，效率较低。此外，FastThreadLocal 相比 ThreadLocal 数据扩容更加简单高效，FastThreadLocal 以 index 为基准向上取整到 2 的次幂作为扩容后容量，然后把原数据拷贝到新数组。而 ThreadLocal 由于采用的哈希表，所以在扩容后需要再做一轮 rehash。</li>
<li><strong>安全性更高</strong>。JDK 原生的 ThreadLocal 使用不当可能造成内存泄漏，只能等待线程销毁。在使用线程池的场景下，ThreadLocal 只能通过主动检测的方式防止内存泄漏，从而造成了一定的开销。然而 FastThreadLocal 不仅提供了 remove() 主动清除对象的方法，而且在线程池场景中 Netty 还封装了 FastThreadLocalRunnable，<strong>任务执行完毕后一定会执行 FastThreadLocal.removeAll() 将 Set 集合中所有 FastThreadLocal 对象都清理掉</strong></li>
</ul>
<h4 id="2、HashedTimerWheel"><a href="#2、HashedTimerWheel" class="headerlink" title="2、HashedTimerWheel"></a>2、<strong>HashedTimerWheel</strong></h4><p>​	生成月统计报表、每日得分结算、邮件定时推送</p>
<p>​	定时任务三种形式：</p>
<p>​		1、按固定周期定时执行</p>
<p>​		2、延迟一定时间后执行</p>
<p>​		3、指定某个时刻执行</p>
<p>​	定时任务的三个关键方法：</p>
<p>​		Schedule 新增任务至任务集合；</p>
<p>​		Cancel 取消某个任务；</p>
<p>​		Run 执行到期的任务</p>
<p>JDK自带的三种定时器：<strong>Timer</strong>、<strong>DelayedQueue</strong> 和 <strong>ScheduledThreadPoolExecutor</strong></p>
<pre><code>Timer小根堆队列，deadline 任务位于堆顶端，弹出的始终是最优先被执行的任务。Run 操作时间复杂度 O(1)，Schedule 和Cancel 操作的时间复杂度都是 O(logn)。
</code></pre>
<p>不论有多少任务被加入数组，始终由 异步线程TimerThread 负责处理。TimerThread 会定时轮询 TaskQueue 中的任务，如果堆顶的任务的 deadline 已到，那么执行任务；如果是周期性任务，执行完成后重新计算下一次任务的 deadline，并再次放入小根堆；如果是单次执行的任务，执行结束后会从 TaskQueue 中删除。</p>
<p>​	</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">DelayedQueue 采用优先级队列 PriorityQueue延迟获取对象的阻塞队列。DelayQueue中的每个对象都必须实现Delayed 接口，并重写 compareTo 和 getDelay 方法。</span><br></pre></td></tr></table></figure>

<p>DelayQueue 提供了 put() 和 take() 的阻塞方法，可以向队列中添加对象和取出对象。对象被添加到 DelayQueue 后，会根据 compareTo() 方法进行优先级排序。getDelay() 方法用于计算消息延迟的剩余时间，只有 getDelay &lt;&#x3D;0 时，该对象才能从 DelayQueue 中取出。</p>
<p>DelayQueue 在日常开发中最常用的场景就是实现重试机制。例如，接口调用失败或者请求超时后，可以将当前请求对象放入 DelayQueue，通过一个异步线程 take() 取出对象然后继续进行重试。如果还是请求失败，继续放回 DelayQueue。可以设置重试的最大次数以及采用指数退避算法设置对象的 deadline，如 2s、4s、8s、16s ……以此类推。DelayQueue的时间复杂度和Timer基本一致。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">为了解决 Timer 的设计缺陷，JDK 提供了功能更加丰富的 ScheduledThreadPoolExecutor，多线程、相对时间、对异常</span><br></pre></td></tr></table></figure>

<p>​	Timer 是单线程模式。如果某个 TimerTask 执行时间很久，会影响其他任务的调度。</p>
<p>​	Timer 的任务调度是基于系统绝对时间的，如果系统时间不正确，可能会出现问题。</p>
<p>​	TimerTask 如果执行出现异常，Timer 并不会捕获，会导致线程终止，其他任务永远不会执行。</p>
<p><strong>时间轮原理分析</strong></p>
<img src="https://tva1.sinaimg.cn/large/008i3skNly1gq6jo7abpbj30wi0ciacs.jpg" alt="image-20210504175518335" style="zoom:50%;" />

<p>根据任务的到期时间进行取余和取模，然后根据取余结果将任务分布到不同的 slot 中，每个slot中根据round值决定是否操作，每次轮询到指定slot时，总时遍历最少round的对象进行执行，这样新增、执行两个操作的时间复杂度都近似O(1)。如果冲突较大可以增加数组长度，或者采用多级时间轮的方式处理。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="title function_">HashedWheelTimer</span><span class="params">(</span></span><br><span class="line"><span class="params">        ThreadFactory threadFactory, //线程池，但是只创建了一个线程</span></span><br><span class="line"><span class="params">        <span class="type">long</span> tickDuration, //时针每次 tick 的时间，相当于时针间隔多久走到下一个 slot</span></span><br><span class="line"><span class="params">        TimeUnit unit, 			//表示 tickDuration 的时间单位，tickDuration * unit</span></span><br><span class="line"><span class="params">        <span class="type">int</span> ticksPerWheel,  //时间轮上一共有多少个 slot，默认 <span class="number">512</span> 个。</span></span><br><span class="line"><span class="params">        <span class="type">boolean</span> leakDetection,</span></span><br><span class="line"><span class="params">        <span class="type">long</span> maxPendingTimeouts)</span> &#123;<span class="comment">//最大允许等待任务数</span></span><br><span class="line">    <span class="comment">// 省略其他代码</span></span><br><span class="line">    wheel = createWheel(ticksPerWheel); <span class="comment">// 创建时间轮的环形数组结构</span></span><br><span class="line">    mask = wheel.length - <span class="number">1</span>; <span class="comment">// 用于快速取模的掩码</span></span><br><span class="line">    <span class="type">long</span> <span class="variable">duration</span> <span class="operator">=</span> unit.toNanos(tickDuration); <span class="comment">// 转换成纳秒处理</span></span><br><span class="line">    workerThread = threadFactory.newThread(worker); <span class="comment">// 创建工作线程</span></span><br><span class="line">    leak = leakDetection || !workerThread.isDaemon() ? leakDetector.track(<span class="built_in">this</span>) : <span class="literal">null</span>; <span class="comment">// 是否开启内存泄漏检测</span></span><br><span class="line">    <span class="built_in">this</span>.maxPendingTimeouts = maxPendingTimeouts; <span class="comment">// 最大允许等待任务数，HashedWheelTimer 中任务超出该阈值时会抛出异常</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<img src="https://tva1.sinaimg.cn/large/008i3skNly1gq6jofq9r4j315i0fmq96.jpg" alt="image-20210504175531294" style="zoom:50%;" />

<p>​	<strong>时间轮空推进问题</strong></p>
<p>​	Netty 中的时间轮是通过固定的时间间隔 tickDuration 进行推动的，如果长时间没有到期任务，那么会存在时间轮空推进的现象，从而造成一定的性能损耗。此外，如果任务的到期时间跨度很大，例如 A 任务 1s 后执行，B 任务 6 小时之后执行，也会造成空推进的问题。</p>
<p><strong>Kafka解决方案</strong></p>
<p>​	<strong>为了解决空推进的问题</strong>，Kafka 借助 JDK 的 DelayQueue 来负责推进时间轮。DelayQueue 保存了时间轮中的每个 Bucket，并且根据 Bucket 的到期时间进行排序，最近的到期时间被放在 DelayQueue 的队头。Kafka 中会有一个线程来读取 DelayQueue 中的任务列表，<strong>如果时间没有到，那么 DelayQueue 会一直处于阻塞状态</strong>，从而解决空推进的问题。虽然DelayQueue 插入和删除的性能不是很好，但这其实就是一种权衡的策略，但是DelayQueue 只存放了 Bucket，Bucket 的数量并不多，相比空推进带来的影响是利大于弊的。</p>
<p>​	<strong>为了解决任务时间跨度很大的问题</strong>，Kafka 引入了层级时间轮，如下图所示。当任务的 deadline 超出当前所在层的时间轮表示范围时，就会尝试将任务添加到上一层时间轮中，跟钟表的时针、分针、秒针的转动规则是同一个道理。</p>
<h4 id="3、MpscQueue"><a href="#3、MpscQueue" class="headerlink" title="3、MpscQueue"></a>3、MpscQueue</h4><h4 id="4、select、poll、epoll的区别"><a href="#4、select、poll、epoll的区别" class="headerlink" title="4、select、poll、epoll的区别"></a>4、select、poll、epoll的区别</h4><p><strong>select</strong> （windows）**poll **(linux)本质上和select没有区别，查询每个fd对应的设备状态，如果设备就绪则在设备等待队列中加入一项并继续遍历，如果遍历完所有fd后没有发现就绪设备，则挂起当前进程，直到设备就绪或者主动超时，被唤醒后它又要再次遍历fd。</p>
<p>**epoll **支持水平触发和边缘触发，最大的特点在于边缘触发，它只告诉进程哪些fd刚刚变为就绪态，并且只会通知一次。还有一个特点是，epoll使用“事件”的就绪通知方式，通过epoll_ctl注册fd，一旦该fd就绪，内核就会采用类似callback的回调机制来激活该fd，epoll_wait便可以收到通知。</p>
<p><strong>Epoll空轮询漏洞</strong></p>
<p>在 JDK 中， Epoll 的实现是存在漏洞的，即使 Selector 轮询的事件列表为空，NIO 线程一样可以被唤醒，导致 CPU 100% 占用。实际上 Netty 并没有从根源上解决该问题，而是巧妙地规避了这个问题。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="type">long</span> <span class="variable">time</span> <span class="operator">=</span> System.nanoTime();</span><br><span class="line"><span class="keyword">if</span> (<span class="comment">/*事件轮询的持续时间大于等于 timeoutMillis*/</span>) &#123;</span><br><span class="line">    selectCnt = <span class="number">1</span>;</span><br><span class="line">&#125; <span class="keyword">else</span> <span class="keyword">if</span> (<span class="comment">/*不正常的次数 selectCnt 达到阈值 512*/</span>) &#123;</span><br><span class="line">    <span class="comment">//重建Select并且SelectionKey重新注册到新Selector上</span></span><br><span class="line">  	selector = selectRebuildSelector(selectCnt);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>NioEventLoop 线程的可靠性至关重要，一旦 NioEventLoop 发生阻塞或者陷入空轮询，就会导致整个系统不可用。</p>
<h1 id="四、LEETCODE"><a href="#四、LEETCODE" class="headerlink" title="四、LEETCODE"></a>四、LEETCODE</h1><h3 id="【Python语法】"><a href="#【Python语法】" class="headerlink" title="【Python语法】"></a>【Python语法】</h3><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br><span class="line">86</span><br><span class="line">87</span><br><span class="line">88</span><br><span class="line">89</span><br><span class="line">90</span><br><span class="line">91</span><br><span class="line">92</span><br><span class="line">93</span><br><span class="line">94</span><br><span class="line">95</span><br><span class="line">96</span><br><span class="line">97</span><br><span class="line">98</span><br><span class="line">99</span><br><span class="line">100</span><br><span class="line">101</span><br><span class="line">102</span><br><span class="line">103</span><br><span class="line">104</span><br><span class="line">105</span><br><span class="line">106</span><br><span class="line">107</span><br><span class="line">108</span><br><span class="line">109</span><br><span class="line">110</span><br><span class="line">111</span><br><span class="line">112</span><br><span class="line">113</span><br><span class="line">114</span><br><span class="line">115</span><br><span class="line">116</span><br><span class="line">117</span><br><span class="line">118</span><br><span class="line">119</span><br><span class="line">120</span><br><span class="line">121</span><br><span class="line">122</span><br><span class="line">123</span><br><span class="line">124</span><br><span class="line">125</span><br><span class="line">126</span><br></pre></td><td class="code"><pre><span class="line">reduce(function, iterable[, initializer])</span><br><span class="line">    reduce(<span class="keyword">lambda</span> x,y:x * y,ns) <span class="comment"># 数组之乘积 (ns[0] * ns[1]) * ns[2]</span></span><br><span class="line">    reduce(<span class="keyword">lambda</span> x,y:x + y,ns) <span class="comment"># 数组之和</span></span><br><span class="line"><span class="comment"># 记忆化搜索</span></span><br><span class="line"><span class="meta">@functools.lru_cache(<span class="params"><span class="literal">None</span></span>)</span></span><br><span class="line">res = helper(<span class="number">0</span>,N,<span class="number">0</span>)</span><br><span class="line">helper.cache_clear()</span><br><span class="line"><span class="built_in">tuple</span>(ns) 可以<span class="built_in">hash</span>做参数</span><br><span class="line"><span class="comment"># 大根堆</span></span><br><span class="line">q = <span class="built_in">list</span>(<span class="built_in">map</span>(<span class="keyword">lambda</span> x:-x,ns))</span><br><span class="line">heapq.heapify(q)</span><br><span class="line">key = -heapq.heappop(q)</span><br><span class="line"><span class="comment"># 过滤函数</span></span><br><span class="line"><span class="built_in">filter</span>(function, iterable)</span><br><span class="line">    <span class="built_in">filter</span>(<span class="keyword">lambda</span> x: <span class="number">2</span> &lt; x &lt; <span class="number">10</span> <span class="keyword">and</span> x % <span class="number">2</span> == <span class="number">0</span>, <span class="built_in">range</span>(<span class="number">18</span>))</span><br><span class="line">    <span class="built_in">filter</span>(dfs, <span class="built_in">range</span>(<span class="built_in">len</span>(graph)))</span><br><span class="line"><span class="comment"># 除数</span></span><br><span class="line">div, mod = <span class="built_in">divmod</span>(<span class="built_in">sum</span>(ns), <span class="number">4</span>)</span><br><span class="line">random.randint(i,<span class="built_in">len</span>(self.ns)-<span class="number">1</span>)</span><br><span class="line"><span class="comment">#第一个降序，第二个升序</span></span><br><span class="line"><span class="built_in">sorted</span>(pss,key = <span class="keyword">lambda</span> x:[x[<span class="number">0</span>],-x[<span class="number">1</span>]])</span><br><span class="line"></span><br><span class="line"><span class="comment"># 不可变str 常见函数</span></span><br><span class="line">split(sep=<span class="literal">None</span>, maxsplit=-<span class="number">1</span>)  <span class="comment"># 以sep来分割字符串</span></span><br><span class="line">strip([chars])  <span class="comment"># 去除首末两端的字符, 默认是 \r,\n,&quot; &quot;</span></span><br><span class="line">join(iterable)  <span class="comment"># 将iterable内的元素拼接成字符串,如&#x27;,&#x27;.join([&#x27;leet&#x27;, &#x27;code&#x27;])=&quot;leet,code&quot;</span></span><br><span class="line">replace(old, new[, count])  <span class="comment"># 字符串替换, old to new</span></span><br><span class="line">count(sub[, start[, end]])  <span class="comment"># 统计子字符串sub的个数</span></span><br><span class="line">startswith(prefix[, start[, end]])  <span class="comment"># 以prefix开始的字符串</span></span><br><span class="line">endswith(suffix[, start[, end]])  <span class="comment"># 以suffix结束的字符串</span></span><br><span class="line">cs <span class="keyword">in</span> chrs: <span class="comment"># chrs 中包含 cs </span></span><br><span class="line"></span><br><span class="line"><span class="comment"># deque 常见函数</span></span><br><span class="line">queue = deque([iterable[, maxlen]])</span><br><span class="line">queue.append(val)  <span class="comment"># 往右边添加一个元素</span></span><br><span class="line">queue.appendleft(val)  <span class="comment"># 往左边添加一个元素</span></span><br><span class="line">queue.clear()  <span class="comment"># 清空队列</span></span><br><span class="line">queue.count(val)  <span class="comment"># 返回指定元素的出现次数</span></span><br><span class="line">queue.insert(val[, start[, stop]])  <span class="comment"># 在指定位置插入元素</span></span><br><span class="line">queue.pop()  <span class="comment"># 获取最右边一个元素，并在队列中删除</span></span><br><span class="line">queue.popleft()  <span class="comment"># 获取最左边一个元素，并在队列中删除</span></span><br><span class="line">queue.reverse()  <span class="comment"># 队列反转</span></span><br><span class="line">queue.remove(val)  <span class="comment"># 删除指定元素</span></span><br><span class="line">queue.rotate(n=<span class="number">1</span>)  <span class="comment"># 把右边元素放到左边</span></span><br><span class="line"></span><br><span class="line"><span class="comment"># list 常见函数</span></span><br><span class="line">lst.sort(*, key=<span class="literal">None</span>, reverse=<span class="literal">False</span>)</span><br><span class="line">lst.append(val)  <span class="comment"># 也可以 lst = lst + [val]</span></span><br><span class="line">lst.clear()  <span class="comment"># 清空列表</span></span><br><span class="line">lst.count(val)  <span class="comment"># val个数</span></span><br><span class="line">lst.pop(val=lst[-<span class="number">1</span>])  <span class="comment"># (默认)从末端移除一个值</span></span><br><span class="line">lst.remove(val)  <span class="comment"># 移除 val</span></span><br><span class="line">lst.reverse()  <span class="comment"># 反转</span></span><br><span class="line">lst.insert(i, val)  <span class="comment"># 在 i 处插入 val</span></span><br><span class="line"></span><br><span class="line"><span class="comment"># 字典dict 常见函数</span></span><br><span class="line">d = defaultdict(<span class="keyword">lambda</span> : value) <span class="comment"># 取到不存在的值时不会报错，用&#123;&#125;时、需要设置get的default值</span></span><br><span class="line">pop(key[, default])  <span class="comment"># 通过键去删除键值对(若没有该键则返回default(没有设置default则报错))</span></span><br><span class="line">setdefault(key[, default])  <span class="comment"># 设置默认值</span></span><br><span class="line">update([other])  <span class="comment"># 批量添加</span></span><br><span class="line">get(key[, default])  <span class="comment"># 通过键获取值(若没有该键可设置默认值, 预防报错)</span></span><br><span class="line">clear()  <span class="comment"># 清空字典</span></span><br><span class="line">keys()  <span class="comment"># 将字典的键组成新的可迭代对象</span></span><br><span class="line">values()  <span class="comment"># 将字典中的值组成新的可迭代对象</span></span><br><span class="line">items()  <span class="comment"># 将字典的键值对凑成一个个元组, 组成新的可迭代对象</span></span><br><span class="line">dict1 = dict2 <span class="comment">#两个字典完全相等，滑窗时可用</span></span><br><span class="line"></span><br><span class="line"><span class="comment"># 集合set 常见函数</span></span><br><span class="line">s = <span class="built_in">set</span>(<span class="keyword">lambda</span> : value)</span><br><span class="line">add(elem)  <span class="comment"># 向集合中添加数据</span></span><br><span class="line">update(*others)  <span class="comment"># 迭代着增加</span></span><br><span class="line">clear()  <span class="comment"># 清空集合</span></span><br><span class="line">discard(elem)  <span class="comment"># 删除集合中指定的值(不存在则不删除)</span></span><br><span class="line"></span><br><span class="line"><span class="comment"># 堆heapq 常见函数</span></span><br><span class="line">heap = []  <span class="comment"># 建堆</span></span><br><span class="line">heapq.heappush(heap,item)  <span class="comment"># 往堆中插入新值</span></span><br><span class="line">heapq.heappop(heap)  <span class="comment"># 弹出最小的值</span></span><br><span class="line">heap[<span class="number">0</span>]  <span class="comment"># 查看堆中最小的值, 不弹出</span></span><br><span class="line">heapq.heapify(x)  <span class="comment"># 以线性时间将一个列表转为堆</span></span><br><span class="line">heapq.heappoppush(heap, item)  <span class="comment"># 弹出最小的值.并且将新的值插入其中.</span></span><br><span class="line">heapq.merge(*iterables, key=<span class="literal">None</span>, reverse=<span class="literal">False</span>)  <span class="comment"># 将多个堆进行合并</span></span><br><span class="line">heapq.nlargest(n, iterable, key=<span class="literal">None</span>)  <span class="comment"># 从堆中找出最大的 n 个数，key的作用和sorted( )方法里面的key类似, 用列表元素的某个属性和函数作为关键字</span></span><br><span class="line">heapq.nsmallest(n, iterable, key=<span class="literal">None</span>)  <span class="comment"># 从堆中找出最小的 n 个数, 与 nlargest 相反</span></span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="comment"># 二分查找函数</span></span><br><span class="line">bisect.bisect_left(ps, T, L=<span class="number">0</span>, R=<span class="built_in">len</span>(ns))  <span class="comment">#二分左边界</span></span><br><span class="line">bisect.bisect_right(ps, T, L=<span class="number">0</span>, R=<span class="built_in">len</span>(ns)) <span class="comment">#二分右边界 </span></span><br><span class="line">bisect.insort_left(a, x, lo=<span class="number">0</span>, hi=<span class="built_in">len</span>(a))  <span class="comment"># 二分插入到左侧</span></span><br><span class="line">bisect.insort_right(a, x, lo=<span class="number">0</span>, hi=<span class="built_in">len</span>(a)) <span class="comment"># 二分插入到右侧</span></span><br><span class="line"></span><br><span class="line"><span class="comment"># bit操作</span></span><br><span class="line">&amp; 符号，x &amp; y ，会将两个十进制数在二进制下进行与运算</span><br><span class="line">| 符号，x | y ，会将两个十进制数在二进制下进行或运算</span><br><span class="line">^ 符号，x ^ y ，会将两个十进制数在二进制下进行异或运算</span><br><span class="line">&lt;&lt; 符号，x &lt;&lt; y 左移操作，最右边用 <span class="number">0</span> 填充</span><br><span class="line">&gt;&gt; 符号，x &gt;&gt; y 右移操作，最左边用 <span class="number">0</span> 填充</span><br><span class="line">~ 符号，~x ，按位取反操作，将 x 在二进制下的每一位取反</span><br><span class="line"></span><br><span class="line"><span class="comment"># 整数集合set位运算</span></span><br><span class="line"><span class="comment"># 整数集合做标志时，可以做参数加速运算</span></span><br><span class="line">vstd 访问 i ：vstd | (<span class="number">1</span> &lt;&lt; i)</span><br><span class="line">vstd 离开 i ：vstd &amp; ~(<span class="number">1</span> &lt;&lt; i)</span><br><span class="line">vstd 不包含 i : <span class="keyword">not</span> vstd &amp; (<span class="number">1</span> &lt;&lt; i)</span><br><span class="line"></span><br><span class="line">并集 ：A | B</span><br><span class="line">交集 ：A &amp; B</span><br><span class="line">全集 ：(<span class="number">1</span> &lt;&lt; n) - <span class="number">1</span></span><br><span class="line">补集 ：((<span class="number">1</span> &lt;&lt; n) - <span class="number">1</span>) ^ A</span><br><span class="line">子集 ：(A &amp; B) == B</span><br><span class="line">判断是否是 <span class="number">2</span> 的幂 ：A &amp; (A - <span class="number">1</span>) == <span class="number">0</span></span><br><span class="line">最低位的 <span class="number">1</span> 变为 <span class="number">0</span> ：n &amp;= (n - <span class="number">1</span>)</span><br><span class="line">        <span class="keyword">while</span> n:</span><br><span class="line">            n &amp;= n - <span class="number">1</span></span><br><span class="line">            ret += <span class="number">1</span></span><br><span class="line">最低位的 <span class="number">1</span>：A &amp; (-A)，最低位的 <span class="number">1</span> 一般记为 lowbit(A)</span><br><span class="line"></span><br><span class="line"><span class="comment"># ^     ：匹配字符串开头</span></span><br><span class="line"><span class="comment"># [\+\-]：代表一个+字符或-字符</span></span><br><span class="line"><span class="comment"># ?     ：前面一个字符可有可无</span></span><br><span class="line"><span class="comment"># \d    ：一个数字</span></span><br><span class="line"><span class="comment"># +     ：前面一个字符的一个或多个</span></span><br><span class="line"><span class="comment"># \D    ：一个非数字字符</span></span><br><span class="line"><span class="comment"># *     ：前面一个字符的0个或多个</span></span><br><span class="line">matches = re.match(<span class="string">&#x27;[ ]*([+-]?\d+)&#x27;</span>, s)</span><br></pre></td></tr></table></figure>



<h3 id="【背包模板】"><a href="#【背包模板】" class="headerlink" title="【背包模板】"></a>【背包模板】</h3><p><strong>「力扣」上的 0-1 背包问题：</strong></p>
<ul>
<li><p>组合问题模板</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">#0-1背包，不可重复</span></span><br><span class="line"><span class="keyword">for</span> n <span class="keyword">in</span> ns: </span><br><span class="line">    <span class="keyword">for</span> i <span class="keyword">in</span> <span class="built_in">range</span>(T, n-<span class="number">1</span>, -<span class="number">1</span>):</span><br><span class="line">        dp[i] = <span class="built_in">max</span>(dp[i], dp[i - n] + ws[i])</span><br><span class="line"><span class="comment">#完全背包，可重复，无序，算重量</span></span><br><span class="line"><span class="keyword">for</span> n <span class="keyword">in</span> ns: </span><br><span class="line">    <span class="keyword">for</span> i <span class="keyword">in</span> <span class="built_in">range</span>(n, T+<span class="number">1</span>):</span><br><span class="line">        dp[i] = <span class="built_in">max</span>(dp[i], dp[i - n] + ws[i]) </span><br><span class="line"><span class="comment">#完全背包，可重复，有序，算次数     </span></span><br><span class="line"><span class="keyword">for</span> i <span class="keyword">in</span> <span class="built_in">range</span>(<span class="number">1</span>, T+<span class="number">1</span>):</span><br><span class="line">    <span class="keyword">for</span> n <span class="keyword">in</span> ns:</span><br><span class="line">		dp[i] += dp[i-n]</span><br></pre></td></tr></table></figure>

<p><strong>✅377</strong> 组合总和 Ⅳ<br>✅<strong>494</strong> 目标和<br>✅<strong>518</strong> 零钱兑换 II</p>
</li>
<li><p>True、False问题</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">dp[i] |= dp[i-num]</span><br></pre></td></tr></table></figure>

<p><strong>✅139</strong> 单词拆分<br><strong>✅416</strong> 分割等和子集</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">#特殊的可以使用bit数组</span></span><br></pre></td></tr></table></figure>
</li>
<li><p>最大最小问题：</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">dp[i] = <span class="built_in">min</span>(dp[i], dp[i-num]+<span class="number">1</span>)</span><br><span class="line">dp[i] = <span class="built_in">max</span>(dp[i], dp[i-num]+<span class="number">1</span>)</span><br></pre></td></tr></table></figure>

<p>✅<strong>474</strong> 一和零<br>✅<strong>322</strong> 零钱兑换</p>
</li>
</ul>
<p>「力扣」第 <strong>879</strong> 题：盈利计划（困难）；<br>「力扣」第 <strong>1449</strong> 题：数位成本和为目标值的最大数字（困难）。</p>
<h3 id="【回溯模板】"><a href="#【回溯模板】" class="headerlink" title="【回溯模板】"></a>【回溯模板】</h3><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># 回溯算法，复杂度较高2^n或者N！，因为回溯算法就是暴力穷举，可用lru剪枝</span></span><br><span class="line"><span class="meta">@functools.lru_cache(<span class="params"><span class="literal">None</span></span>)</span></span><br><span class="line"><span class="keyword">def</span> <span class="title function_">backtrack</span>(<span class="params">路径, 选择列表</span>):</span><br><span class="line">    <span class="keyword">if</span> 满足结束条件:</span><br><span class="line">        结果.append(路径)</span><br><span class="line">        <span class="keyword">return</span></span><br><span class="line">    <span class="keyword">for</span> 选择 <span class="keyword">in</span> 选择列表:    <span class="comment"># 核心代码段</span></span><br><span class="line">      	<span class="keyword">if</span> vst[i]:   <span class="comment"># 辅助数组，减枝</span></span><br><span class="line">          <span class="keyword">continue</span></span><br><span class="line">        做出选择</span><br><span class="line">        递归执行backtrack</span><br><span class="line">        撤销选择</span><br></pre></td></tr></table></figure>

<p>「<strong>剪枝</strong>」第 <strong>46</strong> 题 全排列 第 <strong>47</strong> 题 全排列②</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># 剪枝</span></span><br><span class="line"><span class="keyword">def</span> <span class="title function_">backtrack</span>(<span class="params">temp_list, length</span>):</span><br><span class="line">    <span class="keyword">if</span> length == n:</span><br><span class="line">      res.append(temp_list)</span><br><span class="line">    <span class="keyword">for</span> i <span class="keyword">in</span> <span class="built_in">range</span>(n):</span><br><span class="line">      <span class="keyword">if</span> <span class="keyword">not</span> visited[i]:</span><br><span class="line">          visited[i] = <span class="number">1</span></span><br><span class="line">          backtrack(temp_list + [nums[i]], length + <span class="number">1</span>)</span><br><span class="line">          visited[i] = <span class="number">0</span></span><br></pre></td></tr></table></figure>

<p>「<strong>索引遍历</strong>」第 <strong>78</strong> 题 子集 | 第 <strong>47</strong> 题 子集② | 第 <strong>131</strong> 题 分割字符串</p>
<pre><code>  第 **39 **题 组合 | 第 **40** 题 组合②  | 第 **216** 题 组合③
</code></pre>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># 索引遍历</span></span><br><span class="line"><span class="keyword">def</span> <span class="title function_">helper1</span>(<span class="params">idx, n, temp_list</span>):</span><br><span class="line">  <span class="keyword">if</span> temp_list <span class="keyword">not</span> <span class="keyword">in</span> res:</span><br><span class="line">    res.append(temp_list)</span><br><span class="line">  <span class="keyword">for</span> i <span class="keyword">in</span> <span class="built_in">range</span>(idx, n):</span><br><span class="line">    helper1(i + <span class="number">1</span>, n, temp_list + [nums[i]])</span><br></pre></td></tr></table></figure>

<p>「 <strong>资源消耗</strong>」第 <strong>22</strong> 题 夸号生成</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># 资源消耗</span></span><br><span class="line"><span class="keyword">def</span> <span class="title function_">backtrack</span>(<span class="params">S, L, R</span>):</span><br><span class="line">  <span class="keyword">if</span> <span class="keyword">not</span> L <span class="keyword">and</span> <span class="keyword">not</span> R:</span><br><span class="line">    ans.append(<span class="string">&#x27;&#x27;</span>.join(S))</span><br><span class="line">    <span class="keyword">return</span></span><br><span class="line">  <span class="keyword">if</span> L :     backtrack(S + [<span class="string">&#x27;(&#x27;</span>], L-<span class="number">1</span>, R)</span><br><span class="line">  <span class="keyword">if</span> R &gt; L : backtrack(S + [<span class="string">&#x27;)&#x27;</span>], L, R-<span class="number">1</span>)</span><br></pre></td></tr></table></figure>

<p>「<strong>资源消耗</strong>」第 <strong>93</strong> 题 复原IP</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line">资源消耗</span><br><span class="line"><span class="keyword">def</span> <span class="title function_">backtrack</span>(<span class="params">i, tmp, flag</span>):</span><br><span class="line">  <span class="keyword">if</span> i == n <span class="keyword">and</span> flag == <span class="number">0</span>:</span><br><span class="line">    res.append(tmp[:-<span class="number">1</span>])</span><br><span class="line">  <span class="keyword">elif</span> i&lt;n <span class="keyword">and</span> s[i] == <span class="string">&#x27;0&#x27;</span>:</span><br><span class="line">    backtrack(i + <span class="number">1</span>, tmp + s[i] + <span class="string">&quot;.&quot;</span>, flag - <span class="number">1</span>)</span><br><span class="line">  <span class="keyword">elif</span> flag :</span><br><span class="line">    <span class="keyword">for</span> j <span class="keyword">in</span> <span class="built_in">range</span>(i, <span class="built_in">min</span>(n,i + <span class="number">3</span>)):</span><br><span class="line">      <span class="keyword">if</span> <span class="number">0</span> &lt; <span class="built_in">int</span>(s[i:j + <span class="number">1</span>]) &lt;= <span class="number">255</span>:</span><br><span class="line">        backtrack(j + <span class="number">1</span>, tmp + s[i:j + <span class="number">1</span>] + <span class="string">&quot;.&quot;</span>, flag - <span class="number">1</span>)</span><br></pre></td></tr></table></figure>

<p>「<strong>资源消耗</strong>」第 <strong>17</strong> 题 电话号码</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># 资源消耗</span></span><br><span class="line"><span class="keyword">def</span> <span class="title function_">dfs</span>(<span class="params">path, remains</span>):</span><br><span class="line">  <span class="keyword">if</span> <span class="keyword">not</span> remains:</span><br><span class="line">    res.append(path[:])</span><br><span class="line">    <span class="keyword">return</span></span><br><span class="line">  <span class="keyword">for</span> i <span class="keyword">in</span> <span class="built_in">range</span>(<span class="built_in">len</span>(remains)):</span><br><span class="line">    dfs(path + [remains[i]], remains[:i] + remains[i+<span class="number">1</span>:])</span><br><span class="line"></span><br><span class="line"><span class="comment"># 套模板</span></span><br><span class="line"><span class="keyword">def</span> <span class="title function_">dfs</span>(<span class="params">pth,idx</span>):</span><br><span class="line">    <span class="keyword">if</span> idx == <span class="built_in">len</span>(ds):</span><br><span class="line">        res.append(pth)</span><br><span class="line">        <span class="keyword">return</span></span><br><span class="line">    <span class="keyword">for</span> c <span class="keyword">in</span> dic[ds[idx]]:</span><br><span class="line">        dfs(pth + c, idx + <span class="number">1</span>)</span><br><span class="line"></span><br></pre></td></tr></table></figure>

<p>「<strong>多重限制</strong>」第 <strong>37</strong> 题 解数独  | 第 <strong>51</strong> 题 N皇后</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># 多重限制</span></span><br><span class="line"><span class="keyword">def</span> <span class="title function_">backtrack</span>(<span class="params">pos</span>):</span><br><span class="line">  <span class="keyword">if</span> pos == n:</span><br><span class="line">    <span class="keyword">return</span> <span class="literal">True</span></span><br><span class="line">  i, j = empty[pos]</span><br><span class="line">  <span class="keyword">for</span> num <span class="keyword">in</span> row[i] &amp; col[j] &amp; block[bidx(i, j)]:</span><br><span class="line">    row[i].remove(num)</span><br><span class="line">    col[j].remove(num)</span><br><span class="line">    block[bidx(i, j)].remove(num)</span><br><span class="line">    board[i][j] = <span class="built_in">str</span>(num)</span><br><span class="line">    <span class="keyword">if</span> backtrack(pos + <span class="number">1</span>): <span class="keyword">return</span> <span class="literal">True</span></span><br><span class="line">    row[i].add(num)</span><br><span class="line">    col[j].add(num)</span><br><span class="line">    block[bidx(i, j)].add(num)</span><br></pre></td></tr></table></figure>

<p>「<strong>递归</strong>」第 <strong>10</strong> 题 正则匹配</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># 递归</span></span><br><span class="line"><span class="keyword">def</span> <span class="title function_">isMatch</span>(<span class="params">self, s: <span class="built_in">str</span>, p: <span class="built_in">str</span></span>) -&gt; <span class="built_in">bool</span>:</span><br><span class="line">  <span class="keyword">if</span> <span class="keyword">not</span> p: </span><br><span class="line">    <span class="keyword">return</span> <span class="keyword">not</span> s</span><br><span class="line">  f = <span class="built_in">bool</span>(s <span class="keyword">and</span> p[<span class="number">0</span>] <span class="keyword">in</span> &#123;s[<span class="number">0</span>],<span class="string">&#x27;.&#x27;</span>&#125;)</span><br><span class="line">  <span class="keyword">if</span> <span class="built_in">len</span>(p) &gt;= <span class="number">2</span> <span class="keyword">and</span> p[<span class="number">1</span>] == <span class="string">&quot;*&quot;</span>:</span><br><span class="line">    <span class="keyword">return</span> self.isMatch(s, p[<span class="number">2</span>:]) <span class="keyword">or</span> f <span class="keyword">and</span> self.isMatch(s[<span class="number">1</span>:], p)</span><br><span class="line">  <span class="keyword">else</span>:</span><br><span class="line">    <span class="keyword">return</span> f <span class="keyword">and</span> self.isMatch(s[<span class="number">1</span>:], p[<span class="number">1</span>:])</span><br></pre></td></tr></table></figure>

<h3 id="【并查集模板】"><a href="#【并查集模板】" class="headerlink" title="【并查集模板】"></a>【并查集模板】</h3><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">#虚拟节点用以连接某一特征的全部节点，类似于链表的preHead</span></span><br><span class="line">dummy </span><br><span class="line">parent = &#123;&#125;</span><br><span class="line">size = collections.defaultdict(<span class="keyword">lambda</span>:<span class="number">1</span>)</span><br><span class="line">cnt = <span class="number">0</span></span><br><span class="line"><span class="keyword">def</span> <span class="title function_">find</span>(<span class="params">x</span>):</span><br><span class="line">    parent.setdefault(x,x)</span><br><span class="line">    <span class="keyword">while</span> x != parent[x]:</span><br><span class="line">        x = parent[x]</span><br><span class="line">        <span class="comment">#路径压缩 parent[x] = parent[parent[x]];</span></span><br><span class="line">    <span class="keyword">return</span> x</span><br><span class="line"><span class="keyword">def</span> <span class="title function_">union</span>(<span class="params">x,y</span>):</span><br><span class="line">    <span class="keyword">nonlocal</span> cnt</span><br><span class="line">    <span class="keyword">if</span> connected(x,y): <span class="keyword">return</span></span><br><span class="line">    <span class="comment"># 小的树挂到大的树上， 使树尽量平衡</span></span><br><span class="line">    xP = find(x)</span><br><span class="line">    yP = find(y)</span><br><span class="line">    <span class="keyword">if</span> size[hP] &lt; size[yP]:</span><br><span class="line">        parent[xP] = yP</span><br><span class="line">    <span class="keyword">else</span>:</span><br><span class="line">        parent[yP] = xP</span><br><span class="line">    size[xP] += size[yP]</span><br><span class="line">    <span class="comment"># 优化结束</span></span><br><span class="line">    parent[find(x)] = find(y)</span><br><span class="line">    <span class="comment"># 不优化</span></span><br><span class="line">    cnt -= <span class="number">1</span></span><br><span class="line">    <span class="keyword">return</span> size[xP]</span><br><span class="line"><span class="keyword">def</span> <span class="title function_">connected</span>(<span class="params">x, y</span>):</span><br><span class="line">    <span class="keyword">return</span> find(x) == find(y)</span><br><span class="line"><span class="keyword">def</span> <span class="title function_">add</span>(<span class="params">self,x</span>):</span><br><span class="line">    <span class="keyword">if</span> x <span class="keyword">not</span> <span class="keyword">in</span> parent:</span><br><span class="line">        parent[x] = <span class="literal">None</span></span><br><span class="line">        cnt += <span class="number">1</span></span><br><span class="line"><span class="comment"># 检查是否有环</span></span><br><span class="line"><span class="keyword">for</span> a, b <span class="keyword">in</span> edges:</span><br><span class="line">    <span class="keyword">if</span> connected(a, b): </span><br><span class="line">        <span class="keyword">return</span> <span class="literal">True</span></span><br><span class="line">    union(a, b)</span><br><span class="line"><span class="comment"># 将每个集合组成以头为key的字典</span></span><br><span class="line">res = collections.defaultdict(<span class="built_in">list</span>)</span><br><span class="line"><span class="keyword">for</span> e <span class="keyword">in</span> e2n:</span><br><span class="line">    res[uf.find(e)].append(e)</span><br></pre></td></tr></table></figure>

<h3 id="【拓扑排序模板】"><a href="#【拓扑排序模板】" class="headerlink" title="【拓扑排序模板】"></a>【拓扑排序模板】</h3><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># 【拓扑排序模板】</span></span><br><span class="line">ins = [<span class="number">0</span>] * n</span><br><span class="line">ous = collections.defaultdict(<span class="built_in">list</span>)</span><br><span class="line"><span class="keyword">for</span> cur, pre <span class="keyword">in</span> ps:</span><br><span class="line">    ins[cur] += <span class="number">1</span>  			<span class="comment">#入度</span></span><br><span class="line">    ous[pre].append(cur)	<span class="comment">#出度</span></span><br><span class="line">res = <span class="built_in">list</span>(<span class="built_in">filter</span>(<span class="keyword">lambda</span> x:ins[x]==<span class="number">0</span>, <span class="built_in">range</span>(n)))</span><br><span class="line">q = collections.deque(res)</span><br><span class="line"><span class="keyword">while</span> q:</span><br><span class="line">    pre = q.popleft()</span><br><span class="line">    <span class="keyword">for</span> cur <span class="keyword">in</span> ous[pre]:   <span class="comment">#释放出度队列</span></span><br><span class="line">        ins[cur] -= <span class="number">1</span></span><br><span class="line">        <span class="keyword">if</span> <span class="keyword">not</span> ins[cur]: </span><br><span class="line">            q.append(cur)  <span class="comment">#入度为0解锁</span></span><br><span class="line">            res.append(cur)</span><br></pre></td></tr></table></figure>

<h3 id="【单调栈模板】"><a href="#【单调栈模板】" class="headerlink" title="【单调栈模板】"></a><strong>【单调栈模板】</strong></h3><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># s中一般存索引</span></span><br><span class="line"><span class="keyword">for</span> i <span class="keyword">in</span> <span class="built_in">range</span>(<span class="built_in">len</span>(ns):</span><br><span class="line">    <span class="keyword">while</span> stack <span class="keyword">and</span> ns[stack[-<span class="number">1</span>]] &lt;= ns[i]: <span class="comment"># 单调递减栈</span></span><br><span class="line">        stack.pop()</span><br><span class="line">    <span class="comment"># 业务逻辑</span></span><br><span class="line">    stack.append(i)</span><br></pre></td></tr></table></figure>

<p>「<strong>单调递增</strong>」第 <strong>84</strong> 题 求最大矩形</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># 第 **84** 题 求最大矩形</span></span><br><span class="line"><span class="keyword">for</span> i <span class="keyword">in</span> <span class="built_in">range</span>(<span class="built_in">len</span>(hs)):</span><br><span class="line">    <span class="keyword">while</span> s <span class="keyword">and</span> hs[i] &lt; hs[s[-<span class="number">1</span>]]:</span><br><span class="line">        base = s.pop()</span><br><span class="line">        <span class="keyword">if</span> s:</span><br><span class="line">            H = hs[base]</span><br><span class="line">            W = i - s[-<span class="number">1</span>] - <span class="number">1</span> <span class="comment"># 当前弹出的做高，当前与次小做宽</span></span><br><span class="line">            res = <span class="built_in">max</span>(res, H * W)</span><br><span class="line">    s.append(i)</span><br></pre></td></tr></table></figure>

<p>「<strong>单调递增,考虑剩余</strong>」第 <strong>316</strong> 题 去除重复字符</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># 第 **316** 题 去除重复字符</span></span><br><span class="line"><span class="keyword">for</span> i,c <span class="keyword">in</span> <span class="built_in">enumerate</span>(ss):</span><br><span class="line">    <span class="keyword">if</span> c <span class="keyword">not</span> <span class="keyword">in</span> s:</span><br><span class="line">        <span class="keyword">while</span> s <span class="keyword">and</span> c &lt; s[-<span class="number">1</span>] <span class="keyword">and</span> s[-<span class="number">1</span>] <span class="keyword">in</span> ss[i:]:</span><br><span class="line">            s.pop()</span><br><span class="line">        s.append(c)</span><br></pre></td></tr></table></figure>

<p>「<strong>单调递减</strong>」第 <strong>42</strong> 题 接雨水</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># 第 **42** 题 接雨水</span></span><br><span class="line"><span class="keyword">for</span> i <span class="keyword">in</span> <span class="built_in">range</span>(<span class="built_in">len</span>(hgt)):</span><br><span class="line">    <span class="keyword">while</span> stack <span class="keyword">and</span> hgt[i] &gt; hgt[stack[-<span class="number">1</span>]]: <span class="comment">#递减栈</span></span><br><span class="line">        base = stack.pop()</span><br><span class="line">        <span class="keyword">if</span> stack:</span><br><span class="line">            LH = hgt[stack[-<span class="number">1</span>]]</span><br><span class="line">            W = i - stack[-<span class="number">1</span>] - <span class="number">1</span></span><br><span class="line">            H = <span class="built_in">min</span>(LH,hgt[i]) - hgt[base]</span><br><span class="line">            res += W * H </span><br><span class="line">    stack.append(i)</span><br></pre></td></tr></table></figure>

<p>「<strong>单调递减</strong>」第 <strong>739</strong> 题 每日温度</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># 第 **739** 题 每日温度</span></span><br><span class="line"><span class="keyword">for</span> i <span class="keyword">in</span> <span class="built_in">range</span>(<span class="built_in">len</span>(T)-<span class="number">1</span>,-<span class="number">1</span>,-<span class="number">1</span>):</span><br><span class="line">    <span class="keyword">while</span> s <span class="keyword">and</span> T[s[-<span class="number">1</span>]] &lt;= T[i] :   <span class="comment">#递减栈</span></span><br><span class="line">        s.pop()</span><br><span class="line">    res[i] = s[-<span class="number">1</span>] - i <span class="keyword">if</span> s <span class="keyword">else</span> <span class="number">0</span></span><br><span class="line">    s.append(i)</span><br></pre></td></tr></table></figure>

<h3 id="【二分模板】"><a href="#【二分模板】" class="headerlink" title="【二分模板】"></a>【二分模板】</h3><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># 1355579 T=5 =&gt; 13(5)55579 返回2</span></span><br><span class="line"><span class="comment"># ps[i-1] &lt; ps[i] &lt;= ps[i+1]</span></span><br><span class="line">bisect.bisect_left(ps, T, L=<span class="number">0</span>, R=<span class="built_in">len</span>(ns))  </span><br><span class="line"><span class="comment"># 1355579 T=5 =&gt; 13555(5)79 返回5</span></span><br><span class="line"><span class="comment"># ps[i-1] &lt;= ps[i] &lt; ps[i+1]</span></span><br><span class="line">bisect.bisect_right(ps, T, L=<span class="number">0</span>, R=<span class="built_in">len</span>(ns))  </span><br><span class="line">bisect.bisect(ps, T, L=<span class="number">0</span>, R=<span class="built_in">len</span>(ns))   </span><br></pre></td></tr></table></figure>

<p>「<strong>中位返回</strong>」第 <strong>33</strong> 题 搜索旋转排序数组 | 第<strong>374</strong>题 猜数字大小 | 第<strong>69</strong>题  x平方根</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># 中位返回</span></span><br><span class="line"><span class="keyword">while</span> L &lt;= R:</span><br><span class="line">    M = (L + R) // <span class="number">2</span></span><br><span class="line">    <span class="keyword">if</span> nums[M] == T:</span><br><span class="line">        <span class="keyword">return</span> M</span><br><span class="line">    <span class="keyword">elif</span> nums[M] &lt; T:</span><br><span class="line">        L = M + <span class="number">1</span></span><br><span class="line">    <span class="keyword">else</span>:</span><br><span class="line">        R = M - <span class="number">1</span></span><br></pre></td></tr></table></figure>

<p>「<strong>区域压缩</strong>」第<strong>278</strong>题 第一个错误版本| 第<strong>162</strong>题 寻找峰值 | 第<strong>153</strong>题 寻找数组最小值</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># 区域压缩</span></span><br><span class="line"><span class="keyword">while</span> L &lt; R:</span><br><span class="line">    M = (L + R) // <span class="number">2</span></span><br><span class="line">    <span class="keyword">if</span> need <span class="keyword">in</span> s[L:M]:</span><br><span class="line">        R = M</span><br><span class="line">    <span class="keyword">else</span>:</span><br><span class="line">        L = M + <span class="number">1</span></span><br></pre></td></tr></table></figure>

<h3 id="【动态规划模板】"><a href="#【动态规划模板】" class="headerlink" title="【动态规划模板】"></a>【动态规划模板】</h3><h4 id="「单串问题」"><a href="#「单串问题」" class="headerlink" title="「单串问题」"></a>「<strong>单串问题</strong>」</h4><ul>
<li>70 爬楼梯问题</li>
<li>801 使序列递增的最小交换次数</li>
<li>746 使用最小花费爬楼梯</li>
<li>300 最长上升子序列</li>
</ul>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># 依赖前单个元素</span></span><br><span class="line">dp[i] = dp[i-<span class="number">1</span>] + ns[i]</span><br><span class="line"><span class="comment"># 依赖前部区域元素</span></span><br><span class="line"><span class="keyword">for</span> i <span class="keyword">in</span> <span class="built_in">range</span>(n)</span><br><span class="line">    <span class="keyword">for</span> j <span class="keyword">in</span> <span class="built_in">range</span>(i)</span><br><span class="line">        dp[i] = <span class="built_in">min</span>(dp[i], f(dp[j])</span><br></pre></td></tr></table></figure>

<h4 id="「单串加状态问题」"><a href="#「单串加状态问题」" class="headerlink" title="「单串加状态问题」"></a>「<strong>单串加状态问题</strong>」</h4><ul>
<li><p>887 鸡蛋掉落</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># 鸡蛋掉落</span></span><br><span class="line"><span class="keyword">while</span> cur[K] &lt; N:             <span class="comment"># 还剩 j 个蛋 测 ans 次 覆盖多少层</span></span><br><span class="line">    <span class="keyword">for</span> j <span class="keyword">in</span> <span class="built_in">range</span>(<span class="number">1</span>, K + <span class="number">1</span>): <span class="comment"># 覆盖总层数 碎了 -1 次层数 + 1 + 没碎 -1 次层数</span></span><br><span class="line">        cur[j] = prev[j - <span class="number">1</span>] + <span class="number">1</span> + prev[j]</span><br><span class="line">    ans += <span class="number">1</span></span><br><span class="line">    prev = copy.deepcopy(cur)</span><br></pre></td></tr></table></figure>
</li>
<li><p>813 最大平均值分组</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># 813 最大平均值分组</span></span><br><span class="line"><span class="keyword">for</span> k <span class="keyword">in</span> <span class="built_in">range</span>(K-<span class="number">1</span>):            <span class="comment">#循环k次</span></span><br><span class="line">    <span class="keyword">for</span> i <span class="keyword">in</span> <span class="built_in">range</span>(N):          <span class="comment">#每次均依赖上次的结果</span></span><br><span class="line">        <span class="keyword">for</span> j <span class="keyword">in</span> <span class="built_in">range</span>(i+<span class="number">1</span>, N):</span><br><span class="line">            dp[i] = <span class="built_in">max</span>(dp[i], avrg(i, j) + dp[j])</span><br></pre></td></tr></table></figure>
</li>
<li><p>410 分割数组最大值</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># 410 分割数组最大值</span></span><br><span class="line"><span class="keyword">for</span> k <span class="keyword">in</span> <span class="built_in">range</span>(<span class="number">1</span>,K):</span><br><span class="line">    <span class="keyword">for</span> i <span class="keyword">in</span> <span class="built_in">range</span>(N): </span><br><span class="line">        <span class="keyword">for</span> j <span class="keyword">in</span> <span class="built_in">range</span>(i):</span><br><span class="line">            <span class="comment"># 0~i中分 k 段最大 即为</span></span><br><span class="line">            <span class="comment"># 0~j中分k-1段最大 和 j到i的前缀和的最大</span></span><br><span class="line">            dp[i][k] = <span class="built_in">min</span>(dp[i][k], <span class="built_in">max</span>(dp[j][k-<span class="number">1</span>], ps[i+<span class="number">1</span>] - ps[j+<span class="number">1</span>]))</span><br></pre></td></tr></table></figure></li>
</ul>
<h4 id="「经典双串LCS问题」"><a href="#「经典双串LCS问题」" class="headerlink" title="「经典双串LCS问题」"></a>「<strong>经典双串LCS问题</strong>」</h4><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># 经典双串LCS问题</span></span><br><span class="line">dp = [[<span class="number">0</span>] * (M+<span class="number">1</span>) <span class="keyword">for</span> _ <span class="keyword">in</span> <span class="built_in">range</span>(N+<span class="number">1</span>)]</span><br><span class="line"><span class="keyword">for</span> i <span class="keyword">in</span> <span class="built_in">range</span>(N):</span><br><span class="line">    <span class="keyword">for</span> j <span class="keyword">in</span> <span class="built_in">range</span>(M):</span><br><span class="line">        <span class="keyword">if</span> t1[i] == t2[j] : dp[i+<span class="number">1</span>][j+<span class="number">1</span>] = dp[i][j] + <span class="number">1</span> </span><br><span class="line">        <span class="keyword">else</span> : dp[i+<span class="number">1</span>][j+<span class="number">1</span>] = <span class="built_in">max</span>(dp[i][j+<span class="number">1</span>],dp[i+<span class="number">1</span>][j])</span><br></pre></td></tr></table></figure>

<h4 id="「区间动态规划」"><a href="#「区间动态规划」" class="headerlink" title="「区间动态规划」"></a>「区间动态规划」</h4><ul>
<li>5 最长回文子串</li>
<li>647 最多回文子串</li>
<li>516 最长回文子序列</li>
<li>1312 最长回文插入次数</li>
</ul>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># dp[i][j] 代表从 i 到 j 的最长子串满足条件的数量</span></span><br><span class="line"><span class="comment"># i-- &lt; j++  ==&gt; i 在 0~j 范围内 --</span></span><br><span class="line">dp = [[<span class="number">0</span>] * (N) <span class="keyword">for</span> _ <span class="keyword">in</span> <span class="built_in">range</span>(N)]</span><br><span class="line"><span class="keyword">for</span> j <span class="keyword">in</span> <span class="built_in">range</span>(N):</span><br><span class="line">    dp[j][j] = <span class="number">1</span></span><br><span class="line">    <span class="keyword">for</span> i <span class="keyword">in</span> <span class="built_in">range</span>(j-<span class="number">1</span>,-<span class="number">1</span>,-<span class="number">1</span>):</span><br><span class="line">        <span class="keyword">if</span> ss[i] == ss[j]:</span><br><span class="line">            dp[i][j] = dp[i+<span class="number">1</span>][j-<span class="number">1</span>] +<span class="number">2</span></span><br><span class="line">        <span class="keyword">else</span> :</span><br><span class="line">            dp[i][j] = <span class="built_in">max</span>(dp[i+<span class="number">1</span>][j],dp[i][j-<span class="number">1</span>])</span><br></pre></td></tr></table></figure>

<h4 id="「区间分治动态规划」"><a href="#「区间分治动态规划」" class="headerlink" title="「区间分治动态规划」"></a><strong>「区间分治动态规划」</strong></h4><p><a target="_blank" rel="noopener" href="https://leetcode-cn.com/problems/predict-the-winner/">486 预测赢家</a></p>
<p><a href="***https://leetcode-cn.com/problems/burst-balloons/***">312 戳气球</a></p>
<p><a href="***https://leetcode-cn.com/problems/strange-printer/***">664 奇怪的打印机</a></p>
<p><a href="***https://leetcode-cn.com/problems/remove-boxes/***">546 移除盒子</a></p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># 区间分治动态规划</span></span><br><span class="line"><span class="keyword">def</span> <span class="title function_">helper</span>(<span class="params">self, ns: <span class="type">List</span>[<span class="built_in">int</span>]</span>) :</span><br><span class="line">    N = <span class="built_in">len</span>(ns)</span><br><span class="line">    dp = [[<span class="number">0</span>] * N <span class="keyword">for</span> _ <span class="keyword">in</span> <span class="built_in">range</span>(N+<span class="number">1</span>)]</span><br><span class="line">    <span class="keyword">for</span> l <span class="keyword">in</span> <span class="built_in">range</span>(N): <span class="comment"># 长度从小到大</span></span><br><span class="line">        <span class="keyword">for</span> i <span class="keyword">in</span> <span class="built_in">range</span>(N-l): <span class="comment"># 以 i 为 开头</span></span><br><span class="line">            j = i + l           <span class="comment"># 以 j 为 终点</span></span><br><span class="line">            <span class="keyword">for</span> k <span class="keyword">in</span> <span class="built_in">range</span>(i,j): <span class="comment"># 以 k 为分割点，进行分治         </span></span><br><span class="line">                // Todo 业务逻辑 </span><br></pre></td></tr></table></figure>

<p>「<strong>卡特兰数</strong>」</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># 卡特兰数</span></span><br><span class="line">g(n) = g(<span class="number">0</span>)*g(n-<span class="number">1</span>) + g(<span class="number">1</span>)*g(n-<span class="number">2</span>) ...g(n-<span class="number">1</span>)*g(<span class="number">0</span>)</span><br><span class="line">dp=[<span class="number">1</span>] + [<span class="number">0</span>] * n</span><br><span class="line"><span class="keyword">for</span> i <span class="keyword">in</span> <span class="built_in">range</span>(<span class="number">1</span>,n+<span class="number">1</span>):</span><br><span class="line">    <span class="keyword">for</span> j <span class="keyword">in</span> <span class="built_in">range</span>(<span class="number">1</span>,i+<span class="number">1</span>):</span><br><span class="line">        dp[i] += dp[j-<span class="number">1</span>] * dp[i-j]</span><br></pre></td></tr></table></figure>





<h3 id="【滑动窗口】"><a href="#【滑动窗口】" class="headerlink" title="【滑动窗口】"></a>【滑动窗口】</h3><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br></pre></td><td class="code"><pre><span class="line"><span class="string">&quot;&quot;&quot;给定待查串s和目标串t&quot;&quot;&quot;</span></span><br><span class="line">nd, wd = &#123;&#125;, &#123;&#125;</span><br><span class="line">nd = collections.Counter(s1)</span><br><span class="line">L, R = <span class="number">0</span>, <span class="number">0</span></span><br><span class="line">cnt = <span class="number">0</span> <span class="comment"># 满足条件个数</span></span><br><span class="line"><span class="keyword">while</span> R &lt; <span class="built_in">len</span>(s):        <span class="comment"># 窗口右边界不断扩大，本质是搜索问题的可能解</span></span><br><span class="line">    c = s[R]      <span class="comment"># 即将加入到窗口中的字符</span></span><br><span class="line">    R += <span class="number">1</span></span><br><span class="line">    更新窗口中的数据</span><br><span class="line">    <span class="keyword">while</span> 满足窗口收缩条件：  <span class="comment"># 窗口的左边界收缩，本质是优化可行解</span></span><br><span class="line">        记录或返回结果</span><br><span class="line">        d = s[L]   <span class="comment"># 即将从窗口中删除的字符</span></span><br><span class="line">        L += <span class="number">1</span></span><br><span class="line">        更新窗口中的数据</span><br><span class="line"><span class="keyword">return</span> 结果</span><br><span class="line"></span><br><span class="line"><span class="comment"># 固定窗口 ,比滑动窗口更快一些</span></span><br><span class="line">i = j = cnt = <span class="number">0</span>      </span><br><span class="line"><span class="keyword">for</span> j <span class="keyword">in</span> <span class="built_in">range</span>(<span class="built_in">len</span>(A)):</span><br><span class="line">    <span class="keyword">if</span> A[j] == <span class="number">0</span>: </span><br><span class="line">        cnt += <span class="number">1</span></span><br><span class="line">    <span class="keyword">if</span> cnt &gt; K: <span class="comment">#不满足时 平移</span></span><br><span class="line">        <span class="keyword">if</span> A[i] == <span class="number">0</span>:</span><br><span class="line">            cnt -= <span class="number">1</span></span><br><span class="line">        i += <span class="number">1</span></span><br><span class="line"><span class="keyword">return</span> j - i + <span class="number">1</span>        </span><br><span class="line"> </span><br><span class="line"><span class="keyword">for</span> j <span class="keyword">in</span> <span class="built_in">range</span>(<span class="built_in">len</span>(A)):</span><br><span class="line">    <span class="keyword">if</span> A[j] == <span class="number">0</span>:</span><br><span class="line">        cnt += <span class="number">1</span></span><br><span class="line">    <span class="keyword">while</span> cnt &gt; K:</span><br><span class="line">        <span class="keyword">if</span> A[i] == <span class="number">0</span>:</span><br><span class="line">            cnt -= <span class="number">1</span></span><br><span class="line">        i += <span class="number">1</span></span><br><span class="line">    res = <span class="built_in">max</span>(res, j - i + <span class="number">1</span>)</span><br><span class="line"><span class="keyword">return</span> res</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"></span><br></pre></td></tr></table></figure>

<h3 id="【前缀和】"><a href="#【前缀和】" class="headerlink" title="【前缀和】"></a>【前缀和】</h3><p>「<strong>累加和存位置</strong>」</p>
<p>1371 最长偶数元音子数组</p>
<p>525 最长相等01子数组</p>
<p>325 最长和为k 子数组</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># 前缀和初始化</span></span><br><span class="line">psd = &#123;<span class="number">0</span>: -<span class="number">1</span>&#125;  </span><br><span class="line"><span class="keyword">for</span> i <span class="keyword">in</span> <span class="built_in">range</span>(<span class="built_in">len</span>(s)):</span><br><span class="line">    t ^= cd.get(s[i], <span class="number">0</span>) <span class="comment"># 业务逻辑</span></span><br><span class="line">    <span class="keyword">if</span> t <span class="keyword">not</span> <span class="keyword">in</span> psd:</span><br><span class="line">        psd[t] = i       <span class="comment"># 第一次存入数组</span></span><br><span class="line">    <span class="keyword">else</span>:</span><br><span class="line">        ans = <span class="built_in">max</span>(ans, i - psd[t]) <span class="comment">#已存入则开始计算</span></span><br></pre></td></tr></table></figure>

<p>「<strong>累加和存数量</strong>」</p>
<p>560 和为K的子数组数量</p>
<p> 统计优美子数组</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># 累加和存数量</span></span><br><span class="line">psd = &#123;<span class="number">0</span>:<span class="number">1</span>&#125;</span><br><span class="line"><span class="keyword">for</span> i <span class="keyword">in</span> <span class="built_in">range</span>(<span class="built_in">len</span>(ns)):</span><br><span class="line">    s += ns[i]</span><br><span class="line">    <span class="keyword">if</span> s - T <span class="keyword">in</span> psd:</span><br><span class="line">        ans += psd[s - T] <span class="comment"># 存数量</span></span><br><span class="line">    psd[s] = psd.get(s,<span class="number">0</span>) + <span class="number">1</span></span><br></pre></td></tr></table></figure>

<p>「<strong>模K状态前缀和</strong>」</p>
<p>523 连续和为 k 倍 的子数组（存索引）</p>
<p>974 和被k 整除 子数组数量（存数量）</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># 模K状态前缀和</span></span><br><span class="line">psd = &#123;<span class="number">0</span>:-<span class="number">1</span>&#125;</span><br><span class="line">ans = s = <span class="number">0</span></span><br><span class="line"><span class="keyword">for</span> i <span class="keyword">in</span> <span class="built_in">range</span>(<span class="built_in">len</span>(ns)):</span><br><span class="line">    s += ns[i]				<span class="comment"># 业务逻辑</span></span><br><span class="line">    <span class="keyword">if</span> T != <span class="number">0</span>: s %= <span class="built_in">abs</span>(T)	<span class="comment"># 模k状态做key，索引做值</span></span><br><span class="line">    <span class="keyword">if</span> s <span class="keyword">not</span> <span class="keyword">in</span> psd:</span><br><span class="line">        psd[s] = i</span><br><span class="line">    <span class="keyword">elif</span> i - psd[s] &gt; <span class="number">1</span>:</span><br><span class="line">        <span class="keyword">return</span> <span class="literal">True</span></span><br></pre></td></tr></table></figure>

<p><strong>「矩阵前缀和」</strong></p>
<ul>
<li>363 不超过K的最大数值和</li>
<li>1074 和为目标值的子矩阵数量</li>
</ul>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># 矩阵前缀和</span></span><br><span class="line"><span class="keyword">for</span> i <span class="keyword">in</span> <span class="built_in">range</span>(m):        <span class="comment">#固定左边界</span></span><br><span class="line">    ps = [<span class="number">0</span>] * n</span><br><span class="line">    <span class="keyword">for</span> j <span class="keyword">in</span> <span class="built_in">range</span>(i, m): <span class="comment">#固定右边界</span></span><br><span class="line">    	psS = <span class="number">0</span>	</span><br><span class="line">        dct = &#123;<span class="number">0</span>:<span class="number">1</span>&#125;       <span class="comment">#初始只有一种可能</span></span><br><span class="line">        <span class="keyword">for</span> k <span class="keyword">in</span> <span class="built_in">range</span>(n): <span class="comment"># 以高做前缀和</span></span><br><span class="line">            ps[k] += mtx[j][k]          <span class="comment"># 每行前缀和</span></span><br><span class="line">            psS += ps[k]                <span class="comment"># n行前缀和</span></span><br><span class="line">            cnt += dct.get(psS - T, <span class="number">0</span>)  <span class="comment"># 满足条件cnt</span></span><br><span class="line">            dct[psS] = dct.get(psS,<span class="number">0</span>) + <span class="number">1</span> <span class="comment"># 保存当前状态</span></span><br><span class="line"><span class="keyword">return</span> cnt</span><br></pre></td></tr></table></figure>







<h3 id="【双指针】"><a href="#【双指针】" class="headerlink" title="【双指针】"></a>【双指针】</h3><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># 双指针</span></span><br><span class="line"><span class="keyword">def</span> <span class="title function_">removeElement</span>(<span class="params">self, ns: <span class="type">List</span>[<span class="built_in">int</span>], val: <span class="built_in">int</span></span>) -&gt; <span class="built_in">int</span>:</span><br><span class="line">    slow = <span class="number">0</span></span><br><span class="line">    n = <span class="built_in">len</span>(ns)</span><br><span class="line">    <span class="keyword">for</span> fast <span class="keyword">in</span> <span class="built_in">range</span>(n):</span><br><span class="line">        <span class="keyword">if</span> ns[fast] != val:</span><br><span class="line">            ns[slow] = ns[fast]</span><br><span class="line">            slow += <span class="number">1</span></span><br><span class="line">    <span class="keyword">return</span> slow</span><br></pre></td></tr></table></figure>



<h3 id="【深度优先】"><a href="#【深度优先】" class="headerlink" title="【深度优先】"></a>【深度优先】</h3><p>「<strong>二叉树遍历模板</strong>」</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br><span class="line">86</span><br><span class="line">87</span><br><span class="line">88</span><br><span class="line">89</span><br><span class="line">90</span><br><span class="line">91</span><br><span class="line">92</span><br><span class="line">93</span><br><span class="line">94</span><br><span class="line">95</span><br><span class="line">96</span><br><span class="line">97</span><br><span class="line">98</span><br><span class="line">99</span><br><span class="line">100</span><br><span class="line">101</span><br><span class="line">102</span><br><span class="line">103</span><br><span class="line">104</span><br><span class="line">105</span><br><span class="line">106</span><br><span class="line">107</span><br><span class="line">108</span><br><span class="line">109</span><br><span class="line">110</span><br><span class="line">111</span><br><span class="line">112</span><br><span class="line">113</span><br><span class="line">114</span><br><span class="line">115</span><br><span class="line">116</span><br><span class="line">117</span><br><span class="line">118</span><br><span class="line">119</span><br><span class="line">120</span><br><span class="line">121</span><br><span class="line">122</span><br><span class="line">123</span><br><span class="line">124</span><br><span class="line">125</span><br><span class="line">126</span><br><span class="line">127</span><br><span class="line">128</span><br><span class="line">129</span><br><span class="line">130</span><br><span class="line">131</span><br><span class="line">132</span><br><span class="line">133</span><br><span class="line">134</span><br><span class="line">135</span><br><span class="line">136</span><br><span class="line">137</span><br><span class="line">138</span><br><span class="line">139</span><br><span class="line">140</span><br><span class="line">141</span><br><span class="line">142</span><br><span class="line">143</span><br><span class="line">144</span><br><span class="line">145</span><br><span class="line">146</span><br><span class="line">147</span><br><span class="line">148</span><br><span class="line">149</span><br><span class="line">150</span><br><span class="line">151</span><br><span class="line">152</span><br><span class="line">153</span><br><span class="line">154</span><br><span class="line">155</span><br><span class="line">156</span><br><span class="line">157</span><br><span class="line">158</span><br><span class="line">159</span><br><span class="line">160</span><br><span class="line">161</span><br><span class="line">162</span><br><span class="line">163</span><br><span class="line">164</span><br><span class="line">165</span><br><span class="line">166</span><br><span class="line">167</span><br><span class="line">168</span><br><span class="line">169</span><br><span class="line">170</span><br><span class="line">171</span><br><span class="line">172</span><br><span class="line">173</span><br><span class="line">174</span><br><span class="line">175</span><br><span class="line">176</span><br><span class="line">177</span><br><span class="line">178</span><br><span class="line">179</span><br><span class="line">180</span><br><span class="line">181</span><br><span class="line">182</span><br><span class="line">183</span><br><span class="line">184</span><br><span class="line">185</span><br><span class="line">186</span><br><span class="line">187</span><br><span class="line">188</span><br><span class="line">189</span><br><span class="line">190</span><br><span class="line">191</span><br><span class="line">192</span><br><span class="line">193</span><br><span class="line">194</span><br><span class="line">195</span><br><span class="line">196</span><br><span class="line">197</span><br><span class="line">198</span><br><span class="line">199</span><br><span class="line">200</span><br><span class="line">201</span><br><span class="line">202</span><br><span class="line">203</span><br><span class="line">204</span><br><span class="line">205</span><br><span class="line">206</span><br><span class="line">207</span><br><span class="line">208</span><br><span class="line">209</span><br><span class="line">210</span><br><span class="line">211</span><br><span class="line">212</span><br><span class="line">213</span><br><span class="line">214</span><br><span class="line">215</span><br><span class="line">216</span><br><span class="line">217</span><br><span class="line">218</span><br><span class="line">219</span><br><span class="line">220</span><br><span class="line">221</span><br><span class="line">222</span><br><span class="line">223</span><br><span class="line">224</span><br><span class="line">225</span><br><span class="line">226</span><br><span class="line">227</span><br><span class="line">228</span><br><span class="line">229</span><br><span class="line">230</span><br><span class="line">231</span><br><span class="line">232</span><br><span class="line">233</span><br><span class="line">234</span><br><span class="line">235</span><br><span class="line">236</span><br><span class="line">237</span><br><span class="line">238</span><br><span class="line">239</span><br><span class="line">240</span><br><span class="line">241</span><br><span class="line">242</span><br><span class="line">243</span><br><span class="line">244</span><br><span class="line">245</span><br><span class="line">246</span><br><span class="line">247</span><br><span class="line">248</span><br><span class="line">249</span><br><span class="line">250</span><br><span class="line">251</span><br><span class="line">252</span><br><span class="line">253</span><br><span class="line">254</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># 递归</span></span><br><span class="line"><span class="comment"># 时间复杂度：O(n)，n为节点数，访问每个节点恰好一次。</span></span><br><span class="line"><span class="comment"># 空间复杂度：空间复杂度：O(h)，h为树的高度。最坏情况下需要空间O(n)，平均情况为O(logn)</span></span><br><span class="line"></span><br><span class="line"><span class="comment"># 递归1：二叉树遍历最易理解和实现版本</span></span><br><span class="line"><span class="keyword">class</span> <span class="title class_">Solution</span>:</span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">preOrd</span>(<span class="params">self, root: TreeNode</span>) -&gt; <span class="type">List</span>[<span class="built_in">int</span>]:</span><br><span class="line">        <span class="keyword">if</span> <span class="keyword">not</span> root:</span><br><span class="line">            <span class="keyword">return</span> []</span><br><span class="line">        <span class="comment"># 前序递归</span></span><br><span class="line">        <span class="keyword">return</span> [root.val] + self.preOrd(root.left) + self.preOrd(root.right)</span><br><span class="line">        <span class="comment"># # 中序递归 </span></span><br><span class="line">        <span class="comment"># return self.inOrd(root.left) + [root.val] + self.inOrd(root.right)</span></span><br><span class="line">        <span class="comment"># # 后序递归</span></span><br><span class="line">        <span class="comment"># return self.postOrd(root.left) + self.postOrd(root.right) + [root.val]</span></span><br><span class="line"></span><br><span class="line"><span class="comment"># 递归2：通用模板，可以适应不同的题目，添加参数、增加返回条件、修改进入递归条件、自定义返回值</span></span><br><span class="line"><span class="keyword">class</span> <span class="title class_">Solution</span>:</span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">preOrd</span>(<span class="params">self, root: TreeNode</span>) -&gt; <span class="type">List</span>[<span class="built_in">int</span>]:</span><br><span class="line">        <span class="keyword">def</span> <span class="title function_">dfs</span>(<span class="params">cur</span>):</span><br><span class="line">            <span class="keyword">if</span> <span class="keyword">not</span> cur:</span><br><span class="line">                <span class="keyword">return</span>      </span><br><span class="line">            <span class="comment"># 前序递归</span></span><br><span class="line">            res.append(cur.val)</span><br><span class="line">            dfs(cur.left)</span><br><span class="line">            dfs(cur.right) </span><br><span class="line">            <span class="comment"># # 中序递归</span></span><br><span class="line">            <span class="comment"># dfs(cur.left)</span></span><br><span class="line">            <span class="comment"># res.append(cur.val)</span></span><br><span class="line">            <span class="comment"># dfs(cur.right)</span></span><br><span class="line">            <span class="comment"># # 后序递归</span></span><br><span class="line">            <span class="comment"># dfs(cur.left)</span></span><br><span class="line">            <span class="comment"># dfs(cur.right)</span></span><br><span class="line">            <span class="comment"># res.append(cur.val)      </span></span><br><span class="line">        res = []</span><br><span class="line">        dfs(root)</span><br><span class="line">        <span class="keyword">return</span> res</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="comment"># 迭代</span></span><br><span class="line"><span class="comment"># 时间复杂度：O(n)，n为节点数，访问每个节点恰好一次。</span></span><br><span class="line"><span class="comment"># 空间复杂度：O(h)，h为树的高度。取决于树的结构，最坏情况存储整棵树，即O(n)</span></span><br><span class="line"><span class="comment"># 迭代1：前序遍历最常用模板（后序同样可以用）</span></span><br><span class="line"><span class="keyword">class</span> <span class="title class_">Solution</span>:</span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">preOrd</span>(<span class="params">self, root: TreeNode</span>) -&gt; <span class="type">List</span>[<span class="built_in">int</span>]:</span><br><span class="line">        <span class="keyword">if</span> <span class="keyword">not</span> root:</span><br><span class="line">            <span class="keyword">return</span> []        </span><br><span class="line">        res = []</span><br><span class="line">        stack = [root]</span><br><span class="line">        <span class="comment"># # 前序迭代模板：最常用的二叉树DFS迭代遍历模板</span></span><br><span class="line">        <span class="keyword">while</span> stack:</span><br><span class="line">            cur = stack.pop()</span><br><span class="line">            res.append(cur.val)</span><br><span class="line">            <span class="keyword">if</span> cur.right:</span><br><span class="line">                stack.append(cur.right)</span><br><span class="line">            <span class="keyword">if</span> cur.left:</span><br><span class="line">                stack.append(cur.left)</span><br><span class="line">        <span class="keyword">return</span> res</span><br><span class="line">        </span><br><span class="line">        <span class="comment"># # 后序迭代，相同模板：将前序迭代进栈顺序稍作修改，最后得到的结果反转</span></span><br><span class="line">        <span class="comment"># while stack:</span></span><br><span class="line">        <span class="comment">#     cur = stack.pop()</span></span><br><span class="line">        <span class="comment">#     if cur.left:</span></span><br><span class="line">        <span class="comment">#         stack.append(cur.left)</span></span><br><span class="line">        <span class="comment">#     if cur.right:</span></span><br><span class="line">        <span class="comment">#         stack.append(cur.right)</span></span><br><span class="line">        <span class="comment">#     res.append(cur.val)</span></span><br><span class="line">        <span class="comment"># return res[::-1]</span></span><br><span class="line"></span><br><span class="line"><span class="comment"># 迭代1：层序遍历最常用模板</span></span><br><span class="line"><span class="keyword">class</span> <span class="title class_">Solution</span>:</span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">levelOrder</span>(<span class="params">self, root: TreeNode</span>) -&gt; <span class="type">List</span>[<span class="type">List</span>[<span class="built_in">int</span>]]:</span><br><span class="line">        <span class="keyword">if</span> <span class="keyword">not</span> root:</span><br><span class="line">            <span class="keyword">return</span> []</span><br><span class="line">        q = deque([root])</span><br><span class="line">        res = []</span><br><span class="line">        <span class="keyword">while</span> q :</span><br><span class="line">            l = []</span><br><span class="line">            <span class="keyword">for</span> i <span class="keyword">in</span> <span class="built_in">range</span>(<span class="built_in">len</span>(q)) :</span><br><span class="line">                t = q.popleft()</span><br><span class="line">                l.append(t.val)</span><br><span class="line">                <span class="keyword">if</span> t.left : q.append(t.left)</span><br><span class="line">                <span class="keyword">if</span> t.right : q.append(t.right)</span><br><span class="line">            res.append(l)</span><br><span class="line">        <span class="keyword">return</span> res</span><br><span class="line"></span><br><span class="line">        </span><br><span class="line"><span class="comment"># 迭代2：前、中、后序遍历通用模板（只需一个栈的空间）</span></span><br><span class="line"><span class="keyword">class</span> <span class="title class_">Solution</span>:</span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">inOrd</span>(<span class="params">self, root: TreeNode</span>) -&gt; <span class="type">List</span>[<span class="built_in">int</span>]: </span><br><span class="line">        res = []</span><br><span class="line">        stack = []</span><br><span class="line">        cur = root</span><br><span class="line">        <span class="comment"># 中序，模板：先用指针找到每颗子树的最左下角，然后进行进出栈操作</span></span><br><span class="line">        <span class="keyword">while</span> stack <span class="keyword">or</span> cur:</span><br><span class="line">            <span class="keyword">while</span> cur:</span><br><span class="line">                stack.append(cur)</span><br><span class="line">                cur = cur.left</span><br><span class="line">            cur = stack.pop()</span><br><span class="line">            res.append(cur.val)</span><br><span class="line">            cur = cur.right</span><br><span class="line">        <span class="keyword">return</span> res</span><br><span class="line">        </span><br><span class="line">        <span class="comment"># # 前序，相同模板</span></span><br><span class="line">        <span class="comment"># while stack or cur:</span></span><br><span class="line">        <span class="comment">#     while cur:</span></span><br><span class="line">        <span class="comment">#         res.append(cur.val)</span></span><br><span class="line">        <span class="comment">#         stack.append(cur)</span></span><br><span class="line">        <span class="comment">#         cur = cur.left</span></span><br><span class="line">        <span class="comment">#     cur = stack.pop()</span></span><br><span class="line">        <span class="comment">#     cur = cur.right</span></span><br><span class="line">        <span class="comment"># return res</span></span><br><span class="line">        </span><br><span class="line">        <span class="comment"># # 后序，相同模板</span></span><br><span class="line">        <span class="comment"># while stack or cur:</span></span><br><span class="line">        <span class="comment">#     while cur:</span></span><br><span class="line">        <span class="comment">#         res.append(cur.val)</span></span><br><span class="line">        <span class="comment">#         stack.append(cur)</span></span><br><span class="line">        <span class="comment">#         cur = cur.right</span></span><br><span class="line">        <span class="comment">#     cur = stack.pop()</span></span><br><span class="line">        <span class="comment">#     cur = cur.left</span></span><br><span class="line">        <span class="comment"># return res[::-1]</span></span><br><span class="line">        </span><br><span class="line"></span><br><span class="line"><span class="comment"># 迭代3：标记法迭代（需要双倍的空间来存储访问状态）：</span></span><br><span class="line"><span class="comment"># 前、中、后、层序通用模板，只需改变进栈顺序或即可实现前后中序遍历，</span></span><br><span class="line"><span class="comment"># 而层序遍历则使用队列先进先出。0表示当前未访问，1表示已访问。</span></span><br><span class="line"><span class="keyword">class</span> <span class="title class_">Solution</span>:</span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">preOrd</span>(<span class="params">self, root: TreeNode</span>) -&gt; <span class="type">List</span>[<span class="built_in">int</span>]:</span><br><span class="line">        res = []</span><br><span class="line">        stack = [(<span class="number">0</span>, root)]</span><br><span class="line">        <span class="keyword">while</span> stack:</span><br><span class="line">            flag, cur = stack.pop()</span><br><span class="line">            <span class="keyword">if</span> <span class="keyword">not</span> cur: <span class="keyword">continue</span></span><br><span class="line">            <span class="keyword">if</span> flag == <span class="number">0</span>:</span><br><span class="line">                <span class="comment"># 前序，标记法</span></span><br><span class="line">                stack.append((<span class="number">0</span>, cur.right))</span><br><span class="line">                stack.append((<span class="number">0</span>, cur.left))</span><br><span class="line">                stack.append((<span class="number">1</span>, cur))</span><br><span class="line">                </span><br><span class="line">                <span class="comment"># # 后序，标记法</span></span><br><span class="line">                <span class="comment"># stack.append((1, cur))</span></span><br><span class="line">                <span class="comment"># stack.append((0, cur.right))</span></span><br><span class="line">                <span class="comment"># stack.append((0, cur.left))</span></span><br><span class="line">                </span><br><span class="line">                <span class="comment"># # 中序，标记法</span></span><br><span class="line">                <span class="comment"># stack.append((0, cur.right))</span></span><br><span class="line">                <span class="comment"># stack.append((1, cur))</span></span><br><span class="line">                <span class="comment"># stack.append((0, cur.left))  </span></span><br><span class="line">            <span class="keyword">else</span>:</span><br><span class="line">                res.append(cur.val)  </span><br><span class="line">        <span class="keyword">return</span> res</span><br><span class="line">        </span><br><span class="line">        <span class="comment"># # 层序，标记法</span></span><br><span class="line">        <span class="comment"># res = []</span></span><br><span class="line">        <span class="comment"># queue = [(0, root)]</span></span><br><span class="line">        <span class="comment"># while queue:</span></span><br><span class="line">        <span class="comment">#     flag, cur = queue.pop(0)  # 注意是队列，先进先出</span></span><br><span class="line">        <span class="comment">#     if not cur: continue</span></span><br><span class="line">        <span class="comment">#     if flag == 0:</span></span><br><span class="line">                  <span class="comment"># 层序遍历这三个的顺序无所谓，因为是队列，只弹出队首元素</span></span><br><span class="line">        <span class="comment">#         queue.append((1, cur))</span></span><br><span class="line">        <span class="comment">#         queue.append((0, cur.left))</span></span><br><span class="line">        <span class="comment">#         queue.append((0, cur.right))</span></span><br><span class="line">        <span class="comment">#     else:</span></span><br><span class="line">        <span class="comment">#         res.append(cur.val)</span></span><br><span class="line">        <span class="comment"># return res</span></span><br><span class="line"></span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="comment"># 莫里斯遍历</span></span><br><span class="line"><span class="comment"># 时间复杂度：O(n)，n为节点数，看似超过O(n)，有的节点可能要访问两次，实际分析还是O(n)</span></span><br><span class="line"><span class="comment"># 空间复杂度：O(1)，如果在遍历过程中就输出节点值，则只需常数空间就能得到中序遍历结果，空间只需两个指针。</span></span><br><span class="line"><span class="comment"># 如果将结果储存最后输出，则空间复杂度还是O(n)。</span></span><br><span class="line"></span><br><span class="line"><span class="comment"># PS：莫里斯遍历实际上是在原有二叉树的结构基础上，构造了线索二叉树，</span></span><br><span class="line"><span class="comment"># 线索二叉树定义为：原本为空的右子节点指向了中序遍历顺序之后的那个节点，把所有原本为空的左子节点都指向了中序遍历之前的那个节点</span></span><br><span class="line"></span><br><span class="line"><span class="comment"># 此处只给出中序遍历，前序遍历只需修改输出顺序即可</span></span><br><span class="line"><span class="comment"># 而后序遍历，由于遍历是从根开始的，而线索二叉树是将为空的左右子节点连接到相应的顺序上，使其能够按照相应准则输出</span></span><br><span class="line"><span class="comment"># 但是后序遍历的根节点却已经没有额外的空间来标记自己下一个应该访问的节点，</span></span><br><span class="line"><span class="comment"># 所以这里需要建立一个临时节点dump，令其左孩子是root。并且还需要一个子过程，就是倒序输出某两个节点之间路径上的各个节点。</span></span><br><span class="line"></span><br><span class="line"><span class="comment"># 莫里斯遍历，借助线索二叉树中序遍历（附前序遍历）</span></span><br><span class="line"><span class="keyword">class</span> <span class="title class_">Solution</span>:</span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">inOrd</span>(<span class="params">self, root: TreeNode</span>) -&gt; <span class="type">List</span>[<span class="built_in">int</span>]:</span><br><span class="line">        res = []</span><br><span class="line">        <span class="comment"># cur = pre = TreeNode(None)</span></span><br><span class="line">        cur = root</span><br><span class="line"></span><br><span class="line">        <span class="keyword">while</span> cur:</span><br><span class="line">            <span class="keyword">if</span> <span class="keyword">not</span> cur.left:</span><br><span class="line">                res.append(cur.val)</span><br><span class="line">                <span class="comment"># print(cur.val)</span></span><br><span class="line">                cur = cur.right</span><br><span class="line">            <span class="keyword">else</span>:</span><br><span class="line">                pre = cur.left</span><br><span class="line">                <span class="keyword">while</span> pre.right <span class="keyword">and</span> pre.right != cur:</span><br><span class="line">                    pre = pre.right</span><br><span class="line">                <span class="keyword">if</span> <span class="keyword">not</span> pre.right:</span><br><span class="line">                    <span class="comment"># print(cur.val) 这里是前序遍历的代码，前序与中序的唯一差别</span></span><br><span class="line">                    pre.right = cur</span><br><span class="line">                    cur = cur.left</span><br><span class="line">                <span class="keyword">else</span>:</span><br><span class="line">                    pre.right = <span class="literal">None</span></span><br><span class="line">                    res.append(cur.val)</span><br><span class="line">                    <span class="comment"># print(cur.val)</span></span><br><span class="line">                    cur = cur.right</span><br><span class="line">        <span class="keyword">return</span> res</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="comment"># N叉树遍历</span></span><br><span class="line"><span class="comment"># 时间复杂度：时间复杂度：O(M)，其中 M 是 N 叉树中的节点个数。每个节点只会入栈和出栈各一次。</span></span><br><span class="line"><span class="comment"># 空间复杂度：O(M)。在最坏的情况下，这棵 N 叉树只有 2 层，所有第 2 层的节点都是根节点的孩子。</span></span><br><span class="line"><span class="comment"># 将根节点推出栈后，需要将这些节点都放入栈，共有 M−1个节点，因此栈的大小为 O(M)。</span></span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="comment"># N叉树简洁递归</span></span><br><span class="line"><span class="keyword">class</span> <span class="title class_">Solution</span>:</span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">preorder</span>(<span class="params">self, root: <span class="string">&#x27;Node&#x27;</span></span>) -&gt; <span class="type">List</span>[<span class="built_in">int</span>]:</span><br><span class="line">        <span class="keyword">if</span> <span class="keyword">not</span> root: <span class="keyword">return</span> []</span><br><span class="line">        res = [root.val]</span><br><span class="line">        <span class="keyword">for</span> node <span class="keyword">in</span> root.children:</span><br><span class="line">            res.extend(self.preorder(node))</span><br><span class="line">        <span class="keyword">return</span> res</span><br><span class="line"></span><br><span class="line"><span class="comment"># N叉树通用递归模板</span></span><br><span class="line"><span class="keyword">class</span> <span class="title class_">Solution</span>:</span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">preorder</span>(<span class="params">self, root: <span class="string">&#x27;Node&#x27;</span></span>) -&gt; <span class="type">List</span>[<span class="built_in">int</span>]:</span><br><span class="line">        res = []</span><br><span class="line">        <span class="keyword">def</span> <span class="title function_">helper</span>(<span class="params">root</span>):</span><br><span class="line">            <span class="keyword">if</span> <span class="keyword">not</span> root:</span><br><span class="line">                <span class="keyword">return</span></span><br><span class="line">            res.append(root.val)</span><br><span class="line">            <span class="keyword">for</span> child <span class="keyword">in</span> root.children:</span><br><span class="line">                helper(child)</span><br><span class="line">        helper(root)</span><br><span class="line">        <span class="keyword">return</span> res</span><br><span class="line"></span><br><span class="line"><span class="comment"># N叉树迭代方法</span></span><br><span class="line"><span class="keyword">class</span> <span class="title class_">Solution</span>:</span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">preorder</span>(<span class="params">self, root: <span class="string">&#x27;Node&#x27;</span></span>) -&gt; <span class="type">List</span>[<span class="built_in">int</span>]:</span><br><span class="line">        <span class="keyword">if</span> <span class="keyword">not</span> root:</span><br><span class="line">            <span class="keyword">return</span> []</span><br><span class="line">        s = [root]</span><br><span class="line">        <span class="comment"># s.append(root)</span></span><br><span class="line">        res = []</span><br><span class="line">        <span class="keyword">while</span> s:</span><br><span class="line">            node = s.pop()</span><br><span class="line">            res.append(node.val)</span><br><span class="line">            <span class="comment"># for child in node.children[::-1]:</span></span><br><span class="line">            <span class="comment">#     s.append(child)</span></span><br><span class="line">            s.extend(node.children[::-<span class="number">1</span>])</span><br><span class="line">        <span class="keyword">return</span> res</span><br></pre></td></tr></table></figure>



<h3 id="【广度优先】"><a href="#【广度优先】" class="headerlink" title="【广度优先】"></a>【广度优先】</h3><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># 「**无向图的遍历**」</span></span><br><span class="line">q = collections.deque([i])</span><br><span class="line"><span class="keyword">while</span> q:</span><br><span class="line">    cur = q.popleft()</span><br><span class="line">    <span class="keyword">for</span> nxt <span class="keyword">in</span> dt[cur]:</span><br><span class="line">        <span class="keyword">if</span> <span class="keyword">not</span> vst[nxt]:</span><br><span class="line">            vstd[nxt] = <span class="literal">True</span></span><br><span class="line">            q.append(nxt)</span><br></pre></td></tr></table></figure>

<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># 「**二叉树层序遍历**」</span></span><br><span class="line">q = deque([root])</span><br><span class="line">res = []</span><br><span class="line"><span class="keyword">while</span> q :</span><br><span class="line">    l = []</span><br><span class="line">    <span class="keyword">for</span> i <span class="keyword">in</span> <span class="built_in">range</span>(<span class="built_in">len</span>(q)) :</span><br><span class="line">        t = q.popleft()</span><br><span class="line">        l.append(t.val)</span><br><span class="line">        <span class="keyword">if</span> t.left : q.append(t.left)</span><br><span class="line">        <span class="keyword">if</span> t.right : q.append(t.right)</span><br><span class="line">    res.append(l)</span><br><span class="line"><span class="keyword">return</span> res</span><br></pre></td></tr></table></figure>



<h3 id="【图论】"><a href="#【图论】" class="headerlink" title="【图论】"></a>【图论】</h3><hr>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">#「Dijkstra最短路径」</span></span><br><span class="line">dic = collections.defaultdict(<span class="built_in">list</span>)</span><br><span class="line"><span class="keyword">for</span> u, v, w <span class="keyword">in</span> edges:</span><br><span class="line">    dic[u].append([v, w])</span><br><span class="line">    dic[v].append([u, w])</span><br><span class="line">q = [(<span class="number">0</span>, n)]</span><br><span class="line">dist = [-<span class="number">1</span>] * (n + <span class="number">1</span>)</span><br><span class="line"><span class="keyword">while</span> q:</span><br><span class="line">    dis, cur = heapq.heappop(q)</span><br><span class="line">    <span class="keyword">if</span> dist[cur] &lt; <span class="number">0</span>:</span><br><span class="line">        dist[cur] = dis</span><br><span class="line">        <span class="keyword">for</span> nxt, wi <span class="keyword">in</span> dic[cur]:</span><br><span class="line">            heapq.heappush(q, [dis + wi, nxt])</span><br></pre></td></tr></table></figure>

<p><strong>「Floyd 求图中路径」</strong></p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># Floyd算法 求图中任意2点距离</span></span><br><span class="line">ds = defaultdict(<span class="built_in">int</span>)</span><br><span class="line">st = <span class="built_in">set</span>()</span><br><span class="line"><span class="keyword">for</span> i, (x, y) <span class="keyword">in</span> <span class="built_in">enumerate</span>(ess):</span><br><span class="line">    ds[(x, y)] = vs[i]</span><br><span class="line">    ds[(y, x)] = <span class="number">1</span> / vs[i]</span><br><span class="line">    st.update(&#123;x,y&#125;)</span><br><span class="line">arr = <span class="built_in">list</span>(st)</span><br><span class="line"><span class="keyword">for</span> k <span class="keyword">in</span> arr:</span><br><span class="line">    <span class="keyword">for</span> i <span class="keyword">in</span> arr:</span><br><span class="line">        <span class="keyword">for</span> j <span class="keyword">in</span> arr:</span><br><span class="line">            <span class="keyword">if</span> ds[(i, k)] <span class="keyword">and</span> ds[(k, j)]:</span><br><span class="line">                ds[(i, j)] = ds[(i, k)] * ds[(k, j)]</span><br></pre></td></tr></table></figure>



<h1 id="五、实战算法篇"><a href="#五、实战算法篇" class="headerlink" title="五、实战算法篇"></a>五、实战算法篇</h1><h3 id="1、URL黑名单（布隆过滤器）"><a href="#1、URL黑名单（布隆过滤器）" class="headerlink" title="1、URL黑名单（布隆过滤器）"></a><strong>1、</strong>URL黑名单（布隆过滤器）</h3><p><strong>100亿黑名单URL，每个64B，问这个黑名单要怎么存？判断一个URL是否在黑名单中</strong></p>
<p>​	<strong>散列表：</strong></p>
<p>​		如果把黑名单看成一个集合，将其存在 hashmap 中，貌似太大了，需要 640G，明显不科学。</p>
<p>​	<strong>布隆过滤器：</strong></p>
<p>​		它实际上是一个很长的二进制矢量和一系列随机映射函数。</p>
<p>​		它<strong>可以用来判断一个元素是否在一个集合中</strong>。它的优势是只需要占用很小的内存空间以及有着高效的查询效率。对于布隆过滤器而言，它的本质是一个<strong>位数组</strong>：位数组就是数组的每个元素都只占用 1 bit ，并且每个元素只能是 0 或者 1。</p>
<p>​		在数组中的每一位都是二进制位。布隆过滤器除了一个位数组，还有 K 个哈希函数。当一个元素加入布隆过滤器中的时候，会进行如下操作：</p>
<ul>
<li>使用 K 个哈希函数对元素值进行 K 次计算，得到 K 个哈希值。</li>
<li>根据得到的哈希值，在位数组中把对应下标的值置为 1。</li>
</ul>
<h3 id="2、词频统计（分文件）"><a href="#2、词频统计（分文件）" class="headerlink" title="2、词频统计（分文件）"></a>2、词频统计（分文件）</h3><p><strong>2GB内存在20亿整数中找到出现次数最多的数</strong> </p>
<p>​		通常做法是使用哈希表对出现的每一个数做词频统计，哈希表的key是某个整数，value记录整数出现的次数。本题的数据量是20亿，有可能一个数出现20亿次，则为了避免溢出，哈希表的key是32位（4B）,value也是 32位（4B），那么一条哈希表的记录就需要占用8B。</p>
<p>​		当哈希表记录数为2亿个时，需要16亿个字节数（8*2亿），需要至少1.6GB内存(16亿&#x2F;2^30,1GB&#x3D;&#x3D; 2 ^30个字节 &#x3D;&#x3D; 10亿)。则20亿个记录，至少需要16GB的内存，不符合题目要求。</p>
<p>​		解决办法是将20亿个数的大文件利用哈希函数分成16个小文件，根据哈希函数可以把20亿条数据均匀分布到16个文件上，同一种数不可能被哈希函数分到不同的小文件上，假设哈希函数够好。然后对每一个小文件用哈希函数来统计其中每种数出现的次数，这样我们就得到16个文件中出现次数最多的数，接着从16个数中选出次数最大的那个key即可。</p>
<h3 id="3、未出现的数（bit数组）"><a href="#3、未出现的数（bit数组）" class="headerlink" title="3、未出现的数（bit数组）"></a><strong>3、未出现的数</strong>（bit数组）</h3><p><strong>40亿个非负整数中找到没有出现的数</strong> </p>
<p>​		对于原问题，如果使用哈希表来保存出现过的数，那么最坏情况下是40亿个数都不相同，那么哈希表则需要保存40亿条数据，一个32位整数需要4B，那么40亿*4B &#x3D; 160亿个字节，一般大概10亿个字节的数据需要1G的空间，那么大概需要16G的空间，这不符合要求。</p>
<p>　　我们换一种方式，申请一个bit数组，数组大小为4294967295，大概为40亿bit，40亿&#x2F;8 &#x3D; 5亿字节，那么需要0.5G空间， bit数组的每个位置有两种状态0和1，那么怎么使用这个bit数组呢？呵呵，数组的长度刚好满足我们整数的个数范围，那么数组的每个下标值对应4294967295中的一个数，逐个遍历40亿个无符号数，例如，遇到20，则bitArray[20] &#x3D; 1；遇到666，则bitArray[666] &#x3D; 1,遍历完所有的数，将数组相应位置变为1。</p>
<p><strong>40亿个非负整数中找到一个没有出现的数，内存限制10MB</strong> </p>
<p>​		10亿个字节的数据大概需要1GB空间处理，那么10MB内存换算过来就是可以处理1千万字节的数据，也就是8千万bit，对于40亿非负整数如果申请bit数组的话，40亿bit &#x2F; 0.8亿bit &#x3D; 50，那么这样最少也得分50块来处理，下面就以64块来进行分析解答吧。</p>
<p><strong>总结一下进阶的解法：</strong></p>
<p>1．根据10MB的内存限制，确定统计区间的大小，就是第二次遍历时的bitArr大小。</p>
<p>2．利用区间计数的方式，找到那个计数不足的区间，这个区间上肯定有没出现的数。</p>
<p>3．对这个区间上的数做bit map映射，再遍历bit map，找到一个没出现的数即可。</p>
<p><strong>自己的想法</strong></p>
<p>如果只是找一个数，可以高位模运算，写到64个不同的文件，然后在最小的文件中通过bitArray一次处理掉。</p>
<p><strong>40亿个无符号整数，1GB内存，找到所有出现两次的数</strong> </p>
<p>​		对于原问题，可以用bit map的方式来表示数出现的情况。具体地说，是申请一个长度为4294967295×2的bit类型的数组bitArr，用2个位置表示一个数出现的词频，1B占用8个bit，所以长度为4294967295×2的bit类型的数组占用1GB空间。怎么使用这个bitArr数组呢？遍历这40亿个无符号数，如果初次遇到num，就把bitArr[num<em>2 + 1]和bitArr[num</em>2]设置为01，如果第二次遇到num，就把bitArr[num<em>2+1]和bitArr[num</em>2]设置为10，如果第三次遇到num，就把bitArr[num<em>2+1]和bitArr[num</em>2]设置为11。以后再遇到num，发现此时bitArr[num<em>2+1]和bitArr[num</em>2]已经被设置为11，就不再做任何设置。遍历完成后，再依次遍历bitArr，如果发现bitArr[i<em>2+1]和bitArr[i</em>2]设置为10，那么i 就是出现了两次的数。</p>
<h3 id="4、重复URL（分机器）"><a href="#4、重复URL（分机器）" class="headerlink" title="4、重复URL（分机器）"></a><strong>4、重复URL</strong>（分机器）</h3><p><strong>找到100亿个URL中重复的URL</strong></p>
<p>​		原问题的解法使用解决大数据问题的一种常规方法：把大文件通过哈希函数分配到机器，或者通过哈希函数把大文件拆成小文件。一直进行这种划分，直到划分的结果满足资源限制的要求。首先，你要向面试官询问在资源上的限制有哪些，包括内存、计算时间等要求。在明确了限制要求之后，可以将每条URL通过哈希函数分配到若干机器或者拆分成若干小文件，这里的“若干”由具体的资源限制来计算出精确的数量。 </p>
<p>​		例如，将100亿字节的大文件通过哈希函数分配到100台机器上，然后每一台机器分别统计分给自己的URL中是否有重复的URL，<strong>同时哈希函数的性质决定了同一条URL不可能分给不同的机器；</strong>或者在单机上将大文件通过哈希函数拆成1000个小文件，对每一个小文件再利用哈希表遍历，找出重复的URL；或者在分给机器或拆完文件之后，进行排序，排序过后再看是否有重复的URL出现。总之，牢记一点，很多大数据问题都离不开分流，要么是哈希函数把大文件的内容分配给不同的机器，要么是哈希函数把大文件拆成小文件，然后处理每一个小数量的集合。</p>
<h3 id="5、TOPK搜索（小根堆）"><a href="#5、TOPK搜索（小根堆）" class="headerlink" title="5、TOPK搜索（小根堆）"></a><strong>5、TOPK搜索（小根堆）</strong></h3><p><strong>海量搜索词汇，找到最热TOP100词汇的方法</strong> </p>
<p>​		最开始还是用哈希分流的思路来处理，把包含百亿数据量的词汇文件分流到不同的机器上，具体多少台机器由面试官规定或者由更多的限制来决定。对每一台机器来说，如果分到的数据量依然很大，比如，内存不够或其他问题，可以再用哈希函数把每台机器的分流文件拆成更小的文件处理。</p>
<p>​		处理每一个小文件的时候，哈希表统计每种词及其词频，哈希表记录建立完成后，再遍历哈希表，遍历哈希表的过程中使用大小为100的小根堆来选出每一个小文件的top 100（整体未排序的top 100）。每一个小文件都有自己词频的小根堆（整体未排序的top 100），将小根堆里的词按照词频排序，就得到了每个小文件的排序后top 100。然后把各个小文件排序后的top 100进行外排序或者继续利用小根堆，就可以选出每台机器上的top 100。不同机器之间的top100再进行外排序或者继续利用小根堆，最终求出整个百亿数据量中的top 100。对于top K 的问题，除哈希函数分流和用哈希表做词频统计之外，还经常用堆结构和外排序的手段进行处理。</p>
<h3 id="6、中位数（单向二分查找）"><a href="#6、中位数（单向二分查找）" class="headerlink" title="6、中位数（单向二分查找）"></a><strong>6、中位数（单向二分查找）</strong></h3><p><strong>10MB内存，找到100亿整数的中位数</strong> </p>
<p>①内存够：内存够还慌什么啊，直接把100亿个全部排序了，你用冒泡都可以…然后找到中间那个就可以了。但是你以为面试官会给你内存？？ </p>
<p>②内存不够：题目说是整数，我们认为是带符号的int,所以4字节，占32位。 </p>
<p>  假设100亿个数字保存在一个大文件中，依次读一部分文件到内存(不超过内存的限制)，将每个数字用二进制表示，比较二进制的最高位(第32位，符号位，0是正，1是负)，如果数字的最高位为0，则将这个数字写入 file_0文件中；如果最高位为 1，则将该数字写入file_1文件中。 </p>
<p>  从而将100亿个数字分成了两个文件，假设 file_0文件中有 60亿 个数字，file_1文件中有 40亿 个数字。那么中位数就在 file_0 文件中，并且是 file_0 文件中所有数字排序之后的第 10亿 个数字。（file_1中的数都是负数，file_0中的数都是正数，也即这里一共只有40亿个负数，那么排序之后的第50亿个数一定位于file_0中） </p>
<p>  现在，我们只需要处理 file_0 文件了（不需要再考虑file_1文件）。对于 file_0 文件，同样采取上面的措施处理：将file_0文件依次读一部分到内存(不超内存限制)，将每个数字用二进制表示，比较二进制的 次高位（第31位），如果数字的次高位为0，写入file_0_0文件中；如果次高位为1，写入file_0_1文件 中。 </p>
<p>  现假设 file_0_0文件中有30亿个数字，file_0_1中也有30亿个数字，则中位数就是：file_0_0文件中的数字从小到大排序之后的第10亿个数字。 </p>
<p>  抛弃file_0_1文件，继续对 file_0_0文件 根据 次次高位(第30位) 划分，假设此次划分的两个文件为：file_0_0_0中有5亿个数字，file_0_0_1中有25亿个数字，那么中位数就是 file_0_0_1文件中的所有数字排序之后的 第 5亿 个数。 </p>
<p>  按照上述思路，直到划分的文件可直接加载进内存时，就可以直接对数字进行快速排序，找出中位数了。</p>
<h3 id="7、短域名系统（缓存）"><a href="#7、短域名系统（缓存）" class="headerlink" title="7、短域名系统（缓存）"></a><strong>7、短域名系统（缓存）</strong></h3><p><strong>设计短域名系统，将长URL转化成短的URL.</strong></p>
<p>（1）利用放号器，初始值为0，对于每一个短链接生成请求，都递增放号器的值，再将此值转换为62进制（a-zA-Z0-9），比如第一次请求时放号器的值为0，对应62进制为a，第二次请求时放号器的值为1，对应62进制为b，第10001次请求时放号器的值为10000，对应62进制为sBc。</p>
<p>（2）将短链接服务器域名与放号器的62进制值进行字符串连接，即为短链接的URL，比如：<a target="_blank" rel="noopener" href="http://t.cn/sBc%E3%80%82">t.cn&#x2F;sBc。</a></p>
<p>（3）重定向过程：生成短链接之后，需要存储短链接到长链接的映射关系，即sBc -&gt; URL，浏览器访问短链接服务器时，根据URL Path取到原始的链接，然后进行302重定向。映射关系可使用K-V存储，比如Redis或Memcache。</p>
<h3 id="8、海量评论入库（消息队列）"><a href="#8、海量评论入库（消息队列）" class="headerlink" title="8、海量评论入库（消息队列）"></a><strong>8、海量评论入库（消息队列）</strong></h3><p><strong>假设有这么一个场景，有一条新闻，新闻的评论量可能很大，如何设计评论的读和写</strong></p>
<p>前端页面直接给用户展示、通过消息队列异步方式入库</p>
<p>读可以进行读写分离、同时热点评论定时加载到缓存</p>
<h3 id="9、在线-x2F-并发用户数（Redis）"><a href="#9、在线-x2F-并发用户数（Redis）" class="headerlink" title="9、在线&#x2F;并发用户数（Redis）"></a><strong>9、在线&#x2F;并发用户数（Redis）</strong></h3><p>​	<strong>显示网站的用户在线数的解决思路</strong></p>
<p>​		维护在线用户表</p>
<p>​		使用Redis统计</p>
<p><strong>显示网站并发用户数</strong></p>
<ol>
<li>每当用户访问服务时，把该用户的 ID 写入ZSORT队列，权重为当前时间</li>
<li>根据权重(即时间)计算一分钟内该机构的用户数Zrange</li>
<li>删掉一分钟以上过期的用户Zrem</li>
</ol>
<h3 id="10、热门字符串（前缀树）"><a href="#10、热门字符串（前缀树）" class="headerlink" title="10、热门字符串（前缀树）"></a>10、热门字符串（前缀树）</h3><p>假设目前有 1000w 个记录（这些查询串的重复度比较高，虽然总数是 1000w，但如果除去重复后，则不超过 300w 个）。请统计最热门的 10 个查询串，要求使用的内存不能超过 1G。（一个查询串的重复度越高，说明查询它的用户越多，也就越热门。）</p>
<p><strong>HashMap 法</strong></p>
<p>虽然字符串总数比较多，但去重后不超过 300w，因此，可以考虑把所有字符串及出现次数保存在一个 HashMap 中，所占用的空间为 300w*(255+4)≈777M（其中，4 表示整数占用的 4 个字节）。由此可见，1G 的内存空间完全够用。</p>
<p><strong>思路如下</strong>：</p>
<p>首先，遍历字符串，若不在 map 中，直接存入 map，value 记为 1；若在 map 中，则把对应的 value 加 1，这一步时间复杂度 <code>O(N)</code> 。</p>
<p>接着遍历 map，构建一个 10 个元素的小顶堆，若遍历到的字符串的出现次数大于堆顶字符串的出现次数，则进行替换，并将堆调整为小顶堆。</p>
<p>遍历结束后，堆中 10 个字符串就是出现次数最多的字符串。这一步时间复杂度 <code>O(Nlog10)</code> 。</p>
<p><strong>前缀树法</strong></p>
<p>当这些字符串有大量相同前缀时，可以考虑使用前缀树来统计字符串出现的次数，树的结点保存字符串出现次数，0 表示没有出现。</p>
<p><strong>思路如下</strong>：</p>
<p>在遍历字符串时，在前缀树中查找，如果找到，则把结点中保存的字符串次数加 1，否则为这个字符串构建新结点，构建完成后把叶子结点中字符串的出现次数置为 1。</p>
<p>最后依然使用<strong>小顶堆</strong>来对字符串的出现次数进行排序。</p>
<h3 id="11、红包算法"><a href="#11、红包算法" class="headerlink" title="11、红包算法"></a>11、红包算法</h3><p>线性切割法，一个区间切N-1刀。越早越多</p>
<p>二倍均值法，【0 ~ 剩余金额 &#x2F; 剩余人数 * 2】中随机，相对均匀</p>
<p><img src="https://tva1.sinaimg.cn/large/008eGmZEly1goqpbvl5pvj30qu0gcgm0.jpg" alt="img"></p>
<p><img src="https://tva1.sinaimg.cn/large/008eGmZEly1goqpc3hz9dj31450ggq8k.jpg" alt="img"></p>
<h3 id="11、手写快排"><a href="#11、手写快排" class="headerlink" title="11、手写快排"></a>11、手写快排</h3><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br><span class="line">86</span><br><span class="line">87</span><br><span class="line">88</span><br><span class="line">89</span><br><span class="line">90</span><br><span class="line">91</span><br><span class="line">92</span><br><span class="line">93</span><br><span class="line">94</span><br><span class="line">95</span><br><span class="line">96</span><br><span class="line">97</span><br><span class="line">98</span><br><span class="line">99</span><br><span class="line">100</span><br><span class="line">101</span><br><span class="line">102</span><br><span class="line">103</span><br><span class="line">104</span><br><span class="line">105</span><br><span class="line">106</span><br><span class="line">107</span><br><span class="line">108</span><br><span class="line">109</span><br><span class="line">110</span><br><span class="line">111</span><br><span class="line">112</span><br><span class="line">113</span><br><span class="line">114</span><br><span class="line">115</span><br><span class="line">116</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">QuickSort</span> &#123;</span><br><span class="line">	<span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title function_">swap</span><span class="params">(<span class="type">int</span>[] arr, <span class="type">int</span> i, <span class="type">int</span> j)</span> &#123;</span><br><span class="line">		<span class="type">int</span> <span class="variable">tmp</span> <span class="operator">=</span> arr[i];</span><br><span class="line">		arr[i] = arr[j];</span><br><span class="line">		arr[j] = tmp;</span><br><span class="line">	&#125;</span><br><span class="line">	<span class="comment">/* 常规快排 */</span></span><br><span class="line">	<span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title function_">quickSort1</span><span class="params">(<span class="type">int</span>[] arr, <span class="type">int</span> L , <span class="type">int</span> R)</span> &#123;</span><br><span class="line">		<span class="keyword">if</span> (L &gt; R)  <span class="keyword">return</span>;</span><br><span class="line">		<span class="type">int</span> <span class="variable">M</span> <span class="operator">=</span> partition(arr, L, R);</span><br><span class="line">		quickSort1(arr, L, M - <span class="number">1</span>);</span><br><span class="line">		quickSort1(arr, M + <span class="number">1</span>, R);</span><br><span class="line">	&#125;</span><br><span class="line">	<span class="keyword">public</span> <span class="keyword">static</span> <span class="type">int</span> <span class="title function_">partition</span><span class="params">(<span class="type">int</span>[] arr, <span class="type">int</span> L, <span class="type">int</span> R)</span> &#123;</span><br><span class="line">		<span class="keyword">if</span> (L &gt; R) <span class="keyword">return</span> -<span class="number">1</span>;</span><br><span class="line">		<span class="keyword">if</span> (L == R) <span class="keyword">return</span> L;</span><br><span class="line">		<span class="type">int</span> <span class="variable">lessEqual</span> <span class="operator">=</span> L - <span class="number">1</span>;</span><br><span class="line">		<span class="type">int</span> <span class="variable">index</span> <span class="operator">=</span> L;</span><br><span class="line">		<span class="keyword">while</span> (index &lt; R) &#123;</span><br><span class="line">			<span class="keyword">if</span> (arr[index] &lt;= arr[R])</span><br><span class="line">				swap(arr, index, ++lessEqual);</span><br><span class="line">			index++;</span><br><span class="line">		&#125;</span><br><span class="line">		swap(arr, ++lessEqual, R);</span><br><span class="line">		<span class="keyword">return</span> lessEqual;</span><br><span class="line">	&#125;</span><br><span class="line">	<span class="comment">/* 荷兰国旗 */</span></span><br><span class="line">	<span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title function_">quickSort2</span><span class="params">(<span class="type">int</span>[] arr, <span class="type">int</span> L, <span class="type">int</span> R)</span> &#123;</span><br><span class="line">		<span class="keyword">if</span> (L &gt; R)  <span class="keyword">return</span>;</span><br><span class="line">		<span class="type">int</span>[] equalArea = netherlandsFlag(arr, L, R);</span><br><span class="line">		quickSort2(arr, L, equalArea[<span class="number">0</span>] - <span class="number">1</span>);</span><br><span class="line">		quickSort2(arr, equalArea[<span class="number">1</span>] + <span class="number">1</span>, R);</span><br><span class="line">	&#125;</span><br><span class="line">	<span class="keyword">public</span> <span class="keyword">static</span> <span class="type">int</span>[] netherlandsFlag(<span class="type">int</span>[] arr, <span class="type">int</span> L, <span class="type">int</span> R) &#123;</span><br><span class="line">		<span class="keyword">if</span> (L &gt; R) <span class="keyword">return</span> <span class="keyword">new</span> <span class="title class_">int</span>[] &#123; -<span class="number">1</span>, -<span class="number">1</span> &#125;;</span><br><span class="line">		<span class="keyword">if</span> (L == R) <span class="keyword">return</span> <span class="keyword">new</span> <span class="title class_">int</span>[] &#123; L, R &#125;;</span><br><span class="line">		<span class="type">int</span> <span class="variable">less</span> <span class="operator">=</span> L - <span class="number">1</span>;</span><br><span class="line">		<span class="type">int</span> <span class="variable">more</span> <span class="operator">=</span> R;</span><br><span class="line">		<span class="type">int</span> <span class="variable">index</span> <span class="operator">=</span> L;</span><br><span class="line">		<span class="keyword">while</span> (index &lt; more) &#123;</span><br><span class="line">			<span class="keyword">if</span> (arr[index] == arr[R]) &#123;</span><br><span class="line">				index++;</span><br><span class="line">			&#125; <span class="keyword">else</span> <span class="keyword">if</span> (arr[index] &lt; arr[R]) &#123;</span><br><span class="line">				swap(arr, index++, ++less);</span><br><span class="line">			&#125; <span class="keyword">else</span> &#123;</span><br><span class="line">				swap(arr, index, --more);</span><br><span class="line">			&#125;</span><br><span class="line">		&#125;</span><br><span class="line">		swap(arr, more, R);</span><br><span class="line">		<span class="keyword">return</span> <span class="keyword">new</span> <span class="title class_">int</span>[] &#123; less + <span class="number">1</span>, more &#125;;</span><br><span class="line">	&#125;</span><br><span class="line"></span><br><span class="line">	<span class="comment">// for test</span></span><br><span class="line">	<span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title function_">main</span><span class="params">(String[] args)</span> &#123;</span><br><span class="line">		<span class="type">int</span> <span class="variable">testTime</span> <span class="operator">=</span> <span class="number">1</span>;</span><br><span class="line">		<span class="type">int</span> <span class="variable">maxSize</span> <span class="operator">=</span> <span class="number">10000000</span>;</span><br><span class="line">		<span class="type">int</span> <span class="variable">maxValue</span> <span class="operator">=</span> <span class="number">100000</span>;</span><br><span class="line">		<span class="type">boolean</span> <span class="variable">succeed</span> <span class="operator">=</span> <span class="literal">true</span>;</span><br><span class="line">		<span class="type">long</span> T1=<span class="number">0</span>,T2=<span class="number">0</span>;</span><br><span class="line">		<span class="keyword">for</span> (<span class="type">int</span> <span class="variable">i</span> <span class="operator">=</span> <span class="number">0</span>; i &lt; testTime; i++) &#123;</span><br><span class="line">			<span class="type">int</span>[] arr1 = generateRandomArray(maxSize, maxValue);</span><br><span class="line">			<span class="type">int</span>[] arr2 = copyArray(arr1);</span><br><span class="line">			<span class="type">int</span>[] arr3 = copyArray(arr1);</span><br><span class="line"><span class="comment">//			int[] arr1 = &#123;9,8,7,6,5,4,3,2,1&#125;;</span></span><br><span class="line">			<span class="type">long</span> <span class="variable">t1</span> <span class="operator">=</span> System.currentTimeMillis();</span><br><span class="line">			quickSort1(arr1,<span class="number">0</span>,arr1.length-<span class="number">1</span>);</span><br><span class="line">			<span class="type">long</span> <span class="variable">t2</span> <span class="operator">=</span> System.currentTimeMillis();</span><br><span class="line">			quickSort2(arr2,<span class="number">0</span>,arr2.length-<span class="number">1</span>);</span><br><span class="line">			<span class="type">long</span> <span class="variable">t3</span> <span class="operator">=</span> System.currentTimeMillis();</span><br><span class="line">			T1 += (t2-t1);</span><br><span class="line">			T2 += (t3-t2);</span><br><span class="line">			<span class="keyword">if</span> (!isEqual(arr1, arr2) || !isEqual(arr2, arr3)) &#123;</span><br><span class="line">				succeed = <span class="literal">false</span>;</span><br><span class="line">				<span class="keyword">break</span>;</span><br><span class="line">			&#125;</span><br><span class="line">		&#125;</span><br><span class="line">		System.out.println(T1+<span class="string">&quot; &quot;</span>+T2);</span><br><span class="line"><span class="comment">//		System.out.println(succeed ? &quot;Nice!&quot; : &quot;Oops!&quot;);</span></span><br><span class="line">	&#125;</span><br><span class="line"></span><br><span class="line">	<span class="keyword">private</span> <span class="keyword">static</span> <span class="type">int</span>[] generateRandomArray(<span class="type">int</span> maxSize, <span class="type">int</span> maxValue) &#123;</span><br><span class="line">		<span class="type">int</span>[] arr = <span class="keyword">new</span> <span class="title class_">int</span>[(<span class="type">int</span>) ((maxSize + <span class="number">1</span>) * Math.random())];</span><br><span class="line">		<span class="keyword">for</span> (<span class="type">int</span> <span class="variable">i</span> <span class="operator">=</span> <span class="number">0</span>; i &lt; arr.length; i++) &#123;</span><br><span class="line">			arr[i] = (<span class="type">int</span>) ((maxValue + <span class="number">1</span>) * Math.random()) </span><br><span class="line">                		- (<span class="type">int</span>) (maxValue * Math.random());</span><br><span class="line">		&#125;</span><br><span class="line">		<span class="keyword">return</span> arr;</span><br><span class="line">	&#125;</span><br><span class="line">	<span class="keyword">private</span> <span class="keyword">static</span> <span class="type">int</span>[] copyArray(<span class="type">int</span>[] arr) &#123;</span><br><span class="line">		<span class="keyword">if</span> (arr == <span class="literal">null</span>)  <span class="keyword">return</span> <span class="literal">null</span>;</span><br><span class="line">		<span class="type">int</span>[] res = <span class="keyword">new</span> <span class="title class_">int</span>[arr.length];</span><br><span class="line">		<span class="keyword">for</span> (<span class="type">int</span> <span class="variable">i</span> <span class="operator">=</span> <span class="number">0</span>; i &lt; arr.length; i++) &#123;</span><br><span class="line">			res[i] = arr[i];</span><br><span class="line">		&#125;</span><br><span class="line">		<span class="keyword">return</span> res;</span><br><span class="line">	&#125;</span><br><span class="line">	<span class="keyword">private</span> <span class="keyword">static</span> <span class="type">boolean</span> <span class="title function_">isEqual</span><span class="params">(<span class="type">int</span>[] arr1, <span class="type">int</span>[] arr2)</span> &#123;</span><br><span class="line">		<span class="keyword">if</span> ((arr1 == <span class="literal">null</span> &amp;&amp; arr2 != <span class="literal">null</span>) || (arr1 != <span class="literal">null</span> &amp;&amp; arr2 == <span class="literal">null</span>)) </span><br><span class="line">            <span class="keyword">return</span> <span class="literal">false</span>;</span><br><span class="line">		<span class="keyword">if</span> (arr1 == <span class="literal">null</span> &amp;&amp; arr2 == <span class="literal">null</span>) </span><br><span class="line">			<span class="keyword">return</span> <span class="literal">true</span>;</span><br><span class="line">		<span class="keyword">if</span> (arr1.length != arr2.length) </span><br><span class="line">			<span class="keyword">return</span> <span class="literal">false</span>;</span><br><span class="line">		<span class="keyword">for</span> (<span class="type">int</span> <span class="variable">i</span> <span class="operator">=</span> <span class="number">0</span>; i &lt; arr1.length; i++)</span><br><span class="line">			<span class="keyword">if</span> (arr1[i] != arr2[i])</span><br><span class="line">				<span class="keyword">return</span> <span class="literal">false</span>;</span><br><span class="line">		<span class="keyword">return</span> <span class="literal">true</span>;</span><br><span class="line">	&#125;</span><br><span class="line">	<span class="keyword">private</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title function_">printArray</span><span class="params">(<span class="type">int</span>[] arr)</span> &#123;</span><br><span class="line">		<span class="keyword">if</span> (arr == <span class="literal">null</span>) </span><br><span class="line">			<span class="keyword">return</span>;</span><br><span class="line">		<span class="keyword">for</span> (<span class="type">int</span> <span class="variable">i</span> <span class="operator">=</span> <span class="number">0</span>; i &lt; arr.length; i++) </span><br><span class="line">			System.out.print(arr[i] + <span class="string">&quot; &quot;</span>);</span><br><span class="line">		System.out.println();</span><br><span class="line">	&#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h3 id="12、手写归并"><a href="#12、手写归并" class="headerlink" title="12、手写归并"></a>12、手写归并</h3><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title function_">merge</span><span class="params">(<span class="type">int</span>[] arr, <span class="type">int</span> L, <span class="type">int</span> M, <span class="type">int</span> R)</span> &#123;</span><br><span class="line">    <span class="type">int</span>[] help = <span class="keyword">new</span> <span class="title class_">int</span>[R - L + <span class="number">1</span>];</span><br><span class="line">    <span class="type">int</span> <span class="variable">i</span> <span class="operator">=</span> <span class="number">0</span>;</span><br><span class="line">    <span class="type">int</span> <span class="variable">p1</span> <span class="operator">=</span> L;</span><br><span class="line">    <span class="type">int</span> <span class="variable">p2</span> <span class="operator">=</span> M + <span class="number">1</span>;</span><br><span class="line">    <span class="keyword">while</span> (p1 &lt;= M &amp;&amp; p2 &lt;= R)</span><br><span class="line">        help[i++] = arr[p1] &lt;= arr[p2] ? arr[p1++] : arr[p2++];</span><br><span class="line">    <span class="keyword">while</span> (p1 &lt;= M)</span><br><span class="line">        help[i++] = arr[p1++];</span><br><span class="line">    <span class="keyword">while</span> (p2 &lt;= R)</span><br><span class="line">        help[i++] = arr[p2++];</span><br><span class="line">    <span class="keyword">for</span> (i = <span class="number">0</span>; i &lt; help.length; i++)</span><br><span class="line">        arr[L + i] = help[i];</span><br><span class="line">&#125;</span><br><span class="line"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title function_">mergeSort</span><span class="params">(<span class="type">int</span>[] arr, <span class="type">int</span> L, <span class="type">int</span> R)</span> &#123;</span><br><span class="line">    <span class="keyword">if</span> (L == R)</span><br><span class="line">        <span class="keyword">return</span>;</span><br><span class="line">    <span class="type">int</span> <span class="variable">mid</span> <span class="operator">=</span> L + ((R - L) &gt;&gt; <span class="number">1</span>);</span><br><span class="line">    process(arr, L, mid);</span><br><span class="line">    process(arr, mid + <span class="number">1</span>, R);</span><br><span class="line">    merge(arr, L, mid, R);</span><br><span class="line">&#125;</span><br><span class="line"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title function_">main</span><span class="params">(String[] args)</span> &#123;</span><br><span class="line">    <span class="type">int</span>[] arr1 = &#123;<span class="number">9</span>,<span class="number">8</span>,<span class="number">7</span>,<span class="number">6</span>,<span class="number">5</span>,<span class="number">4</span>,<span class="number">3</span>,<span class="number">2</span>,<span class="number">1</span>&#125;;</span><br><span class="line">    mergeSort(arr, <span class="number">0</span>, arr.length - <span class="number">1</span>);</span><br><span class="line">    printArray(arr);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h3 id="13、手写堆排"><a href="#13、手写堆排" class="headerlink" title="13、手写堆排"></a>13、手写堆排</h3><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 堆排序额外空间复杂度O(1)</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title function_">heapSort</span><span class="params">(<span class="type">int</span>[] arr)</span> &#123;</span><br><span class="line">    <span class="keyword">if</span> (arr == <span class="literal">null</span> || arr.length &lt; <span class="number">2</span>) </span><br><span class="line">        <span class="keyword">return</span>;</span><br><span class="line">    <span class="keyword">for</span> (<span class="type">int</span> <span class="variable">i</span> <span class="operator">=</span> arr.length - <span class="number">1</span>; i &gt;= <span class="number">0</span>; i--) </span><br><span class="line">        heapify(arr, i, arr.length);</span><br><span class="line">    <span class="type">int</span> <span class="variable">heapSize</span> <span class="operator">=</span> arr.length;</span><br><span class="line">    swap(arr, <span class="number">0</span>, --heapSize);</span><br><span class="line">    <span class="comment">// O(N*logN)</span></span><br><span class="line">    <span class="keyword">while</span> (heapSize &gt; <span class="number">0</span>) &#123; <span class="comment">// O(N)</span></span><br><span class="line">        heapify(arr, <span class="number">0</span>, heapSize); <span class="comment">// O(logN)</span></span><br><span class="line">        swap(arr, <span class="number">0</span>, --heapSize); <span class="comment">// O(1)</span></span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"><span class="comment">// arr[index]刚来的数，往上</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title function_">heapInsert</span><span class="params">(<span class="type">int</span>[] arr, <span class="type">int</span> index)</span> &#123;</span><br><span class="line">    <span class="keyword">while</span> (arr[index] &gt; arr[(index - <span class="number">1</span>) / <span class="number">2</span>]) &#123;</span><br><span class="line">        swap(arr, index, (index - <span class="number">1</span>) / <span class="number">2</span>);</span><br><span class="line">        index = (index - <span class="number">1</span>) / <span class="number">2</span>;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"><span class="comment">// arr[index]位置的数，能否往下移动</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title function_">heapify</span><span class="params">(<span class="type">int</span>[] arr, <span class="type">int</span> index, <span class="type">int</span> heapSize)</span> &#123;</span><br><span class="line">    <span class="type">int</span> <span class="variable">left</span> <span class="operator">=</span> index * <span class="number">2</span> + <span class="number">1</span>; <span class="comment">// 左孩子的下标</span></span><br><span class="line">    <span class="keyword">while</span> (left &lt; heapSize) &#123; <span class="comment">// 下方还有孩子的时候</span></span><br><span class="line">        <span class="comment">// 两个孩子中，谁的值大，把下标给largest</span></span><br><span class="line">        <span class="comment">// 1）只有左孩子，left -&gt; largest</span></span><br><span class="line">        <span class="comment">// 2) 同时有左孩子和右孩子，右孩子的值&lt;= 左孩子的值，left -&gt; largest</span></span><br><span class="line">        <span class="comment">// 3) 同时有左孩子和右孩子并且右孩子的值&gt; 左孩子的值， right -&gt; largest</span></span><br><span class="line">        <span class="type">int</span> <span class="variable">largest</span> <span class="operator">=</span> left+<span class="number">1</span> &lt; heapSize &amp;&amp; arr[left+<span class="number">1</span>]&gt; arr[left] ? left+<span class="number">1</span> : left;</span><br><span class="line">        <span class="comment">// 父和较大的孩子之间，谁的值大，把下标给largest</span></span><br><span class="line">        largest = arr[largest] &gt; arr[index] ? largest : index;</span><br><span class="line">        <span class="keyword">if</span> (largest == index)</span><br><span class="line">            <span class="keyword">break</span>;</span><br><span class="line">        swap(arr, largest, index);</span><br><span class="line">        index = largest;</span><br><span class="line">        left = index * <span class="number">2</span> + <span class="number">1</span>;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title function_">swap</span><span class="params">(<span class="type">int</span>[] arr, <span class="type">int</span> i, <span class="type">int</span> j)</span> &#123;</span><br><span class="line">    <span class="type">int</span> <span class="variable">tmp</span> <span class="operator">=</span> arr[i];</span><br><span class="line">    arr[i] = arr[j];</span><br><span class="line">    arr[j] = tmp;</span><br><span class="line">&#125;</span><br><span class="line"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title function_">main</span><span class="params">(String[] args)</span> &#123;</span><br><span class="line">    <span class="type">int</span>[] arr1 = &#123;<span class="number">9</span>,<span class="number">8</span>,<span class="number">7</span>,<span class="number">6</span>,<span class="number">5</span>,<span class="number">4</span>,<span class="number">3</span>,<span class="number">2</span>,<span class="number">1</span>&#125;;</span><br><span class="line">    heapSort(arr1);</span><br><span class="line">    printArray(arr1);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>



<h3 id="14、手写单例"><a href="#14、手写单例" class="headerlink" title="14、手写单例"></a>14、手写单例</h3><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">Singleton</span> &#123;</span><br><span class="line">		<span class="keyword">private</span> <span class="keyword">volatile</span> <span class="keyword">static</span> Singleton singleton;</span><br><span class="line">		<span class="keyword">private</span> <span class="title function_">Singleton</span><span class="params">()</span> &#123;&#125;</span><br><span class="line">		<span class="keyword">public</span> <span class="keyword">static</span> Singleton <span class="title function_">getSingleton</span><span class="params">()</span> &#123;</span><br><span class="line">        <span class="keyword">if</span> (singleton == <span class="literal">null</span>) &#123;</span><br><span class="line">          	<span class="keyword">synchronized</span> (Singleton.class) &#123;</span><br><span class="line">            <span class="keyword">if</span> (singleton == <span class="literal">null</span>) &#123;</span><br><span class="line">              	singleton = <span class="keyword">new</span> <span class="title class_">Singleton</span>();</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">		&#125;</span><br><span class="line">		<span class="keyword">return</span> singleton;</span><br><span class="line">	&#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>



<h3 id="15、手写LRUcache"><a href="#15、手写LRUcache" class="headerlink" title="15、手写LRUcache"></a>15、手写LRUcache</h3><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 基于linkedHashMap</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">LRUCache</span> &#123;</span><br><span class="line">    <span class="keyword">private</span> LinkedHashMap&lt;Integer,Integer&gt; cache;</span><br><span class="line">    <span class="keyword">private</span> <span class="type">int</span> capacity;   <span class="comment">//容量大小</span></span><br><span class="line">    <span class="keyword">public</span> <span class="title function_">LRUCache</span><span class="params">(<span class="type">int</span> capacity)</span> &#123;</span><br><span class="line">        cache = <span class="keyword">new</span> <span class="title class_">LinkedHashMap</span>&lt;&gt;(capacity);</span><br><span class="line">        <span class="built_in">this</span>.capacity = capacity;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">public</span> <span class="type">int</span> <span class="title function_">get</span><span class="params">(<span class="type">int</span> key)</span> &#123;</span><br><span class="line">        <span class="comment">//缓存中不存在此key，直接返回</span></span><br><span class="line">        <span class="keyword">if</span>(!cache.containsKey(key)) &#123;</span><br><span class="line">            <span class="keyword">return</span> -<span class="number">1</span>;</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="type">int</span> <span class="variable">res</span> <span class="operator">=</span> cache.get(key);</span><br><span class="line">        cache.remove(key);   <span class="comment">//先从链表中删除</span></span><br><span class="line">        cache.put(key,res);  <span class="comment">//再把该节点放到链表末尾处</span></span><br><span class="line">        <span class="keyword">return</span> res;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">put</span><span class="params">(<span class="type">int</span> key,<span class="type">int</span> value)</span> &#123;</span><br><span class="line">        <span class="keyword">if</span>(cache.containsKey(key)) &#123;</span><br><span class="line">            cache.remove(key); <span class="comment">//已经存在，在当前链表移除</span></span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">if</span>(capacity == cache.size()) &#123;</span><br><span class="line">            <span class="comment">//cache已满，删除链表头位置</span></span><br><span class="line">            Set&lt;Integer&gt; keySet = cache.keySet();</span><br><span class="line">            Iterator&lt;Integer&gt; iterator = keySet.iterator();</span><br><span class="line">            cache.remove(iterator.next());</span><br><span class="line">        &#125;</span><br><span class="line">        cache.put(key,value);  <span class="comment">//插入到链表末尾</span></span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>



<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//手写双向链表</span></span><br><span class="line"><span class="keyword">class</span> <span class="title class_">LRUCache</span> &#123;</span><br><span class="line">    <span class="keyword">class</span> <span class="title class_">DNode</span> &#123;</span><br><span class="line">        DNode prev;</span><br><span class="line">        DNode next;</span><br><span class="line">        <span class="type">int</span> val;</span><br><span class="line">        <span class="type">int</span> key;</span><br><span class="line">    &#125;</span><br><span class="line">    Map&lt;Integer, DNode&gt; map = <span class="keyword">new</span> <span class="title class_">HashMap</span>&lt;&gt;();</span><br><span class="line">    DNode head, tail;</span><br><span class="line">    <span class="type">int</span> cap;</span><br><span class="line">    <span class="keyword">public</span> <span class="title function_">LRUCache</span><span class="params">(<span class="type">int</span> capacity)</span> &#123;</span><br><span class="line">        head = <span class="keyword">new</span> <span class="title class_">DNode</span>();</span><br><span class="line">        tail = <span class="keyword">new</span> <span class="title class_">DNode</span>();</span><br><span class="line">        head.next = tail;</span><br><span class="line">        tail.prev = head;</span><br><span class="line">        cap = capacity;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">public</span> <span class="type">int</span> <span class="title function_">get</span><span class="params">(<span class="type">int</span> key)</span> &#123;</span><br><span class="line">        <span class="keyword">if</span> (map.containsKey(key)) &#123;</span><br><span class="line">            <span class="type">DNode</span> <span class="variable">node</span> <span class="operator">=</span> map.get(key);</span><br><span class="line">            removeNode(node);</span><br><span class="line">            addToHead(node);</span><br><span class="line">            <span class="keyword">return</span> node.val;</span><br><span class="line">        &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">            <span class="keyword">return</span> -<span class="number">1</span>;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">put</span><span class="params">(<span class="type">int</span> key, <span class="type">int</span> value)</span> &#123;</span><br><span class="line">        <span class="keyword">if</span> (map.containsKey(key)) &#123;</span><br><span class="line">            <span class="type">DNode</span> <span class="variable">node</span> <span class="operator">=</span> map.get(key);</span><br><span class="line">            node.val = value;</span><br><span class="line">            removeNode(node);</span><br><span class="line">            addToHead(node);</span><br><span class="line">        &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">            <span class="type">DNode</span> <span class="variable">newNode</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">DNode</span>();</span><br><span class="line">            newNode.val = value;</span><br><span class="line">            newNode.key = key;</span><br><span class="line">            addToHead(newNode);</span><br><span class="line">            map.put(key, newNode);</span><br><span class="line">            <span class="keyword">if</span> (map.size() &gt; cap) &#123;</span><br><span class="line">                map.remove(tail.prev.key);</span><br><span class="line">                removeNode(tail.prev);</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">removeNode</span><span class="params">(DNode node)</span> &#123;</span><br><span class="line">        <span class="type">DNode</span> <span class="variable">prevNode</span> <span class="operator">=</span> node.prev;</span><br><span class="line">        <span class="type">DNode</span> <span class="variable">nextNode</span> <span class="operator">=</span> node.next;</span><br><span class="line">        prevNode.next = nextNode;</span><br><span class="line">        nextNode.prev = prevNode;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">addToHead</span><span class="params">(DNode node)</span> &#123;</span><br><span class="line">        <span class="type">DNode</span> <span class="variable">firstNode</span> <span class="operator">=</span> head.next;</span><br><span class="line">        head.next = node;</span><br><span class="line">        node.prev = head;</span><br><span class="line">        node.next = firstNode;</span><br><span class="line">        firstNode.prev = node;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br></pre></td></tr></table></figure>



<h3 id="16、手写线程池"><a href="#16、手写线程池" class="headerlink" title="16、手写线程池"></a><strong>16、手写线程池</strong></h3><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br><span class="line">86</span><br><span class="line">87</span><br><span class="line">88</span><br><span class="line">89</span><br><span class="line">90</span><br><span class="line">91</span><br><span class="line">92</span><br><span class="line">93</span><br><span class="line">94</span><br><span class="line">95</span><br><span class="line">96</span><br><span class="line">97</span><br><span class="line">98</span><br><span class="line">99</span><br><span class="line">100</span><br><span class="line">101</span><br><span class="line">102</span><br><span class="line">103</span><br><span class="line">104</span><br><span class="line">105</span><br><span class="line">106</span><br><span class="line">107</span><br><span class="line">108</span><br><span class="line">109</span><br><span class="line">110</span><br><span class="line">111</span><br><span class="line">112</span><br><span class="line">113</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">package</span> com.concurrent.pool;</span><br><span class="line"><span class="keyword">import</span> java.util.HashSet;</span><br><span class="line"><span class="keyword">import</span> java.util.Set;</span><br><span class="line"><span class="keyword">import</span> java.util.concurrent.ArrayBlockingQueue;</span><br><span class="line"><span class="keyword">import</span> java.util.concurrent.BlockingQueue;</span><br><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">MySelfThreadPool</span> &#123;</span><br><span class="line">	<span class="comment">//默认线程池中的线程的数量</span></span><br><span class="line">	<span class="keyword">private</span> <span class="keyword">static</span> <span class="keyword">final</span> <span class="type">int</span> <span class="variable">WORK_NUM</span> <span class="operator">=</span> <span class="number">5</span>;</span><br><span class="line">	<span class="comment">//默认处理任务的数量</span></span><br><span class="line">	<span class="keyword">private</span> <span class="keyword">static</span> <span class="keyword">final</span> <span class="type">int</span> <span class="variable">TASK_NUM</span> <span class="operator">=</span> <span class="number">100</span>;</span><br><span class="line">	<span class="keyword">private</span> <span class="type">int</span> workNum;<span class="comment">//线程数量</span></span><br><span class="line">	<span class="keyword">private</span> <span class="type">int</span> taskNum;<span class="comment">//任务数量</span></span><br><span class="line">	<span class="keyword">private</span> <span class="keyword">final</span> Set&lt;WorkThread&gt; workThreads;<span class="comment">//保存线程的集合</span></span><br><span class="line">	<span class="keyword">private</span> <span class="keyword">final</span> BlockingQueue&lt;Runnable&gt; taskQueue;<span class="comment">//阻塞有序队列存放任务</span></span><br><span class="line">	<span class="keyword">public</span> <span class="title function_">MySelfThreadPool</span><span class="params">()</span> &#123;</span><br><span class="line">		<span class="built_in">this</span>(WORK_NUM, TASK_NUM);</span><br><span class="line">	&#125;</span><br><span class="line">	<span class="keyword">public</span> <span class="title function_">MySelfThreadPool</span><span class="params">(<span class="type">int</span> workNum, <span class="type">int</span> taskNum)</span> &#123;</span><br><span class="line">		<span class="keyword">if</span> (workNum &lt;= <span class="number">0</span>) workNum = WORK_NUM;</span><br><span class="line">		<span class="keyword">if</span> (taskNum &lt;= <span class="number">0</span>) taskNum = TASK_NUM;</span><br><span class="line">		taskQueue = <span class="keyword">new</span> <span class="title class_">ArrayBlockingQueue</span>&lt;&gt;(taskNum);</span><br><span class="line">		<span class="built_in">this</span>.workNum = workNum;</span><br><span class="line">		<span class="built_in">this</span>.taskNum = taskNum;</span><br><span class="line">		workThreads = <span class="keyword">new</span> <span class="title class_">HashSet</span>&lt;&gt;();</span><br><span class="line">		<span class="comment">//启动一定数量的线程数，从队列中获取任务处理</span></span><br><span class="line">		<span class="keyword">for</span> (<span class="type">int</span> i=<span class="number">0</span>;i&lt;workNum;i++) &#123;</span><br><span class="line">			<span class="type">WorkThread</span> <span class="variable">workThread</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">WorkThread</span>(<span class="string">&quot;thead_&quot;</span>+i);</span><br><span class="line">			workThread.start();</span><br><span class="line">			workThreads.add(workThread);</span><br><span class="line">		&#125;</span><br><span class="line">	&#125;</span><br><span class="line">	<span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">execute</span><span class="params">(Runnable task)</span> &#123;</span><br><span class="line">		<span class="keyword">try</span> &#123;</span><br><span class="line">			taskQueue.put(task);</span><br><span class="line">		&#125; <span class="keyword">catch</span> (InterruptedException e) &#123;</span><br><span class="line">			<span class="comment">// TODO Auto-generated catch block</span></span><br><span class="line">			e.printStackTrace();</span><br><span class="line">		&#125;</span><br><span class="line">	&#125;</span><br><span class="line">	<span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">destroy</span><span class="params">()</span> &#123;</span><br><span class="line">		System.out.println(<span class="string">&quot;ready close thread pool...&quot;</span>);</span><br><span class="line">		<span class="keyword">if</span> (workThreads == <span class="literal">null</span> || workThreads.isEmpty()) <span class="keyword">return</span> ;</span><br><span class="line">		<span class="keyword">for</span> (WorkThread workThread : workThreads) &#123;</span><br><span class="line">			workThread.stopWork();</span><br><span class="line">			workThread = <span class="literal">null</span>;<span class="comment">//help gc</span></span><br><span class="line">		&#125;</span><br><span class="line">		workThreads.clear();</span><br><span class="line">	&#125;</span><br><span class="line">	<span class="keyword">private</span> <span class="keyword">class</span> <span class="title class_">WorkThread</span> <span class="keyword">extends</span> <span class="title class_">Thread</span>&#123;</span><br><span class="line">		<span class="keyword">public</span> <span class="title function_">WorkThread</span><span class="params">(String name)</span> &#123;</span><br><span class="line">			<span class="built_in">super</span>();</span><br><span class="line">			setName(name);</span><br><span class="line">		&#125;</span><br><span class="line">		<span class="meta">@Override</span></span><br><span class="line">		<span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">run</span><span class="params">()</span> &#123;</span><br><span class="line">			<span class="keyword">while</span> (!interrupted()) &#123;</span><br><span class="line">				<span class="keyword">try</span> &#123;</span><br><span class="line">					<span class="type">Runnable</span> <span class="variable">runnable</span> <span class="operator">=</span> taskQueue.take();<span class="comment">//获取任务</span></span><br><span class="line">					<span class="keyword">if</span> (runnable !=<span class="literal">null</span>) &#123;</span><br><span class="line">						System.out.println(getName()+<span class="string">&quot; readyexecute:&quot;</span>+runnable.toString());</span><br><span class="line">						runnable.run();<span class="comment">//执行任务</span></span><br><span class="line">					&#125;</span><br><span class="line">					runnable = <span class="literal">null</span>;<span class="comment">//help gc</span></span><br><span class="line">				&#125; <span class="keyword">catch</span> (Exception e) &#123;</span><br><span class="line">					interrupt();</span><br><span class="line">					e.printStackTrace();</span><br><span class="line">				&#125;</span><br><span class="line">			&#125;</span><br><span class="line">		&#125;</span><br><span class="line">		<span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">stopWork</span><span class="params">()</span> &#123;</span><br><span class="line">			interrupt();</span><br><span class="line">		&#125;</span><br><span class="line">	&#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">package</span> com.concurrent.pool;</span><br><span class="line"> </span><br><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">TestMySelfThreadPool</span> &#123;</span><br><span class="line">	<span class="keyword">private</span> <span class="keyword">static</span> <span class="keyword">final</span> <span class="type">int</span> <span class="variable">TASK_NUM</span> <span class="operator">=</span> <span class="number">50</span>;<span class="comment">//任务的个数</span></span><br><span class="line">	<span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title function_">main</span><span class="params">(String[] args)</span> &#123;</span><br><span class="line">		<span class="type">MySelfThreadPool</span> <span class="variable">myPool</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">MySelfThreadPool</span>(<span class="number">3</span>,<span class="number">50</span>);</span><br><span class="line">		<span class="keyword">for</span> (<span class="type">int</span> i=<span class="number">0</span>;i&lt;TASK_NUM;i++) &#123;</span><br><span class="line">			myPool.execute(<span class="keyword">new</span> <span class="title class_">MyTask</span>(<span class="string">&quot;task_&quot;</span>+i));</span><br><span class="line">		&#125;</span><br><span class="line">	&#125;</span><br><span class="line">	<span class="keyword">static</span> <span class="keyword">class</span> <span class="title class_">MyTask</span> <span class="keyword">implements</span> <span class="title class_">Runnable</span>&#123;</span><br><span class="line">		<span class="keyword">private</span> String name;</span><br><span class="line">		<span class="keyword">public</span> <span class="title function_">MyTask</span><span class="params">(String name)</span> &#123;</span><br><span class="line">			<span class="built_in">this</span>.name = name;</span><br><span class="line">		&#125;</span><br><span class="line">		<span class="keyword">public</span> String <span class="title function_">getName</span><span class="params">()</span> &#123;</span><br><span class="line">			<span class="keyword">return</span> name;</span><br><span class="line">		&#125;</span><br><span class="line">		<span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">setName</span><span class="params">(String name)</span> &#123;</span><br><span class="line">			<span class="built_in">this</span>.name = name;</span><br><span class="line">		&#125;</span><br><span class="line">		<span class="meta">@Override</span></span><br><span class="line">		<span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">run</span><span class="params">()</span> &#123;</span><br><span class="line">			<span class="keyword">try</span> &#123;</span><br><span class="line">				Thread.sleep(<span class="number">1000</span>);</span><br><span class="line">			&#125; <span class="keyword">catch</span> (InterruptedException e) &#123;</span><br><span class="line">				<span class="comment">// TODO Auto-generated catch block</span></span><br><span class="line">				e.printStackTrace();</span><br><span class="line">			&#125;</span><br><span class="line">			System.out.println(<span class="string">&quot;task :&quot;</span>+name+<span class="string">&quot; end...&quot;</span>);</span><br><span class="line">		&#125;</span><br><span class="line">		<span class="meta">@Override</span></span><br><span class="line">		<span class="keyword">public</span> String <span class="title function_">toString</span><span class="params">()</span> &#123;</span><br><span class="line">			<span class="comment">// TODO Auto-generated method stub</span></span><br><span class="line">			<span class="keyword">return</span> <span class="string">&quot;name = &quot;</span>+name;</span><br><span class="line">		&#125;</span><br><span class="line">	&#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>





<h3 id="17、手写消费者生产者模式"><a href="#17、手写消费者生产者模式" class="headerlink" title="17、手写消费者生产者模式"></a><strong>17、手写消费者生产者模式</strong></h3><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br><span class="line">86</span><br><span class="line">87</span><br><span class="line">88</span><br><span class="line">89</span><br><span class="line">90</span><br><span class="line">91</span><br><span class="line">92</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">Storage</span> &#123;</span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">static</span> <span class="type">int</span> <span class="variable">MAX_VALUE</span> <span class="operator">=</span> <span class="number">100</span>;</span><br><span class="line">    <span class="keyword">private</span> List&lt;Object&gt; list = <span class="keyword">new</span> <span class="title class_">ArrayList</span>&lt;&gt;();</span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">produce</span><span class="params">(<span class="type">int</span> num)</span> &#123;</span><br><span class="line">        <span class="keyword">synchronized</span> (list) &#123;</span><br><span class="line">            <span class="keyword">while</span> (list.size() + num &gt; MAX_VALUE) &#123;</span><br><span class="line">                System.out.println(<span class="string">&quot;暂时不能执行生产任务&quot;</span>);</span><br><span class="line">                <span class="keyword">try</span> &#123;</span><br><span class="line">                    list.wait();</span><br><span class="line">                &#125; <span class="keyword">catch</span> (InterruptedException e) &#123;</span><br><span class="line">                    e.printStackTrace();</span><br><span class="line">                &#125;</span><br><span class="line">            &#125;</span><br><span class="line">            <span class="keyword">for</span> (<span class="type">int</span> <span class="variable">i</span> <span class="operator">=</span> <span class="number">0</span>; i &lt; num; i++) &#123;</span><br><span class="line">                list.add(<span class="keyword">new</span> <span class="title class_">Object</span>());</span><br><span class="line">            &#125;</span><br><span class="line">            System.out.println(<span class="string">&quot;已生产产品数&quot;</span>+num+<span class="string">&quot; 仓库容量&quot;</span>+list.size());</span><br><span class="line">            list.notifyAll();</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">consume</span><span class="params">(<span class="type">int</span> num)</span> &#123;</span><br><span class="line">        <span class="keyword">synchronized</span> (list) &#123;</span><br><span class="line">            <span class="keyword">while</span> (list.size() &lt; num) &#123;</span><br><span class="line">                System.out.println(<span class="string">&quot;暂时不能执行消费任务&quot;</span>);</span><br><span class="line">                <span class="keyword">try</span> &#123;</span><br><span class="line">                    list.wait();</span><br><span class="line">                &#125; <span class="keyword">catch</span> (InterruptedException e) &#123;</span><br><span class="line">                    e.printStackTrace();</span><br><span class="line">                &#125;</span><br><span class="line">            &#125;</span><br><span class="line">            <span class="keyword">for</span> (<span class="type">int</span> <span class="variable">i</span> <span class="operator">=</span> <span class="number">0</span>; i &lt; num; i++) &#123;</span><br><span class="line">                list.remove(<span class="number">0</span>);</span><br><span class="line">            &#125;</span><br><span class="line">            System.out.println(<span class="string">&quot;已消费产品数&quot;</span>+num+<span class="string">&quot; 仓库容量&quot;</span> + list.size());</span><br><span class="line">            list.notifyAll();</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">Producer</span> <span class="keyword">extends</span> <span class="title class_">Thread</span> &#123;</span><br><span class="line">    <span class="keyword">private</span> <span class="type">int</span> num;</span><br><span class="line">    <span class="keyword">private</span> Storage storage;</span><br><span class="line">    <span class="keyword">public</span> <span class="title function_">Producer</span><span class="params">(Storage storage)</span> &#123;</span><br><span class="line">        <span class="built_in">this</span>.storage = storage;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">setNum</span><span class="params">(<span class="type">int</span> num)</span> &#123;</span><br><span class="line">        <span class="built_in">this</span>.num = num;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">run</span><span class="params">()</span> &#123;</span><br><span class="line">        storage.produce(<span class="built_in">this</span>.num);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">Customer</span> <span class="keyword">extends</span> <span class="title class_">Thread</span> &#123;</span><br><span class="line">    <span class="keyword">private</span> <span class="type">int</span> num;</span><br><span class="line">    <span class="keyword">private</span> Storage storage;</span><br><span class="line">    <span class="keyword">public</span> <span class="title function_">Customer</span><span class="params">(Storage storage)</span> &#123;</span><br><span class="line">        <span class="built_in">this</span>.storage = storage;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">setNum</span><span class="params">(<span class="type">int</span> num)</span> &#123;</span><br><span class="line">        <span class="built_in">this</span>.num = num;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">run</span><span class="params">()</span> &#123;</span><br><span class="line">        storage.consume(<span class="built_in">this</span>.num);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">Test</span> &#123;</span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title function_">main</span><span class="params">(String[] args)</span> &#123;</span><br><span class="line">        <span class="type">Storage</span> <span class="variable">storage</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">Storage</span>();</span><br><span class="line">        <span class="type">Producer</span> <span class="variable">p1</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">Producer</span>(storage);</span><br><span class="line">        <span class="type">Producer</span> <span class="variable">p2</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">Producer</span>(storage);</span><br><span class="line">        <span class="type">Producer</span> <span class="variable">p3</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">Producer</span>(storage);</span><br><span class="line">        <span class="type">Producer</span> <span class="variable">p4</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">Producer</span>(storage);</span><br><span class="line">        <span class="type">Customer</span> <span class="variable">c1</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">Customer</span>(storage);</span><br><span class="line">        <span class="type">Customer</span> <span class="variable">c2</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">Customer</span>(storage);</span><br><span class="line">        <span class="type">Customer</span> <span class="variable">c3</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">Customer</span>(storage);</span><br><span class="line">        p1.setNum(<span class="number">10</span>);</span><br><span class="line">        p2.setNum(<span class="number">20</span>);</span><br><span class="line">        p3.setNum(<span class="number">80</span>);</span><br><span class="line">        c1.setNum(<span class="number">50</span>);</span><br><span class="line">        c2.setNum(<span class="number">20</span>);</span><br><span class="line">        c3.setNum(<span class="number">20</span>);</span><br><span class="line">        c1.start();</span><br><span class="line">        c2.start();</span><br><span class="line">        c3.start();</span><br><span class="line">        p1.start();</span><br><span class="line">        p2.start();</span><br><span class="line">        p3.start();</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>





<h3 id="18、手写阻塞队列"><a href="#18、手写阻塞队列" class="headerlink" title="18、手写阻塞队列"></a><strong>18、手写阻塞队列</strong></h3><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">blockQueue</span> &#123;</span><br><span class="line">    <span class="keyword">private</span> List&lt;Integer&gt; container = <span class="keyword">new</span> <span class="title class_">ArrayList</span>&lt;&gt;();</span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">volatile</span> <span class="type">int</span> size;</span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">volatile</span> <span class="type">int</span> capacity;</span><br><span class="line">    <span class="keyword">private</span> <span class="type">Lock</span> <span class="variable">lock</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">ReentrantLock</span>();</span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">final</span> <span class="type">Condition</span> <span class="variable">isNull</span> <span class="operator">=</span> lock.newCondition();</span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">final</span> <span class="type">Condition</span> <span class="variable">isFull</span> <span class="operator">=</span> lock.newCondition();</span><br><span class="line">    blockQueue(<span class="type">int</span> capacity) &#123;</span><br><span class="line">        <span class="built_in">this</span>.capacity = capacity;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">add</span><span class="params">(<span class="type">int</span> data)</span> &#123;</span><br><span class="line">        <span class="keyword">try</span> &#123;</span><br><span class="line">            lock.lock();</span><br><span class="line">            <span class="keyword">try</span> &#123;</span><br><span class="line">                <span class="keyword">while</span> (size &gt;= capacity) &#123;</span><br><span class="line">                    System.out.println(<span class="string">&quot;阻塞队列满了&quot;</span>);</span><br><span class="line">                    isFull.await();</span><br><span class="line">                &#125;</span><br><span class="line">            &#125; <span class="keyword">catch</span> (Exception e) &#123;</span><br><span class="line">                isFull.signal();</span><br><span class="line">                e.printStackTrace();</span><br><span class="line">            &#125;</span><br><span class="line">            ++size;</span><br><span class="line">            container.add(data);</span><br><span class="line">            isNull.signal();</span><br><span class="line">        &#125; <span class="keyword">finally</span> &#123;</span><br><span class="line">            lock.unlock();</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">public</span> <span class="type">int</span> <span class="title function_">take</span><span class="params">()</span> &#123;</span><br><span class="line">        <span class="keyword">try</span> &#123;</span><br><span class="line">            lock.lock();</span><br><span class="line">            <span class="keyword">try</span> &#123;</span><br><span class="line">                <span class="keyword">while</span> (size == <span class="number">0</span>) &#123;</span><br><span class="line">                    System.out.println(<span class="string">&quot;阻塞队列空了&quot;</span>);</span><br><span class="line">                    isNull.await();</span><br><span class="line">                &#125;</span><br><span class="line">            &#125; <span class="keyword">catch</span> (Exception e) &#123;</span><br><span class="line">                isNull.signal();</span><br><span class="line">                e.printStackTrace();</span><br><span class="line">            &#125;</span><br><span class="line">            --size;</span><br><span class="line">            <span class="type">int</span> <span class="variable">res</span> <span class="operator">=</span> container.get(<span class="number">0</span>);</span><br><span class="line">            container.remove(<span class="number">0</span>);</span><br><span class="line">            isFull.signal();</span><br><span class="line">            <span class="keyword">return</span> res;</span><br><span class="line">        &#125; <span class="keyword">finally</span> &#123;</span><br><span class="line">            lock.unlock();</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title function_">main</span><span class="params">(String[] args)</span> &#123;</span><br><span class="line">    <span class="type">AxinBlockQueue</span> <span class="variable">queue</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">AxinBlockQueue</span>(<span class="number">5</span>);</span><br><span class="line">    <span class="type">Thread</span> <span class="variable">t1</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">Thread</span>(() -&gt; &#123;</span><br><span class="line">        <span class="keyword">for</span> (<span class="type">int</span> <span class="variable">i</span> <span class="operator">=</span> <span class="number">0</span>; i &lt; <span class="number">100</span>; i++) &#123;</span><br><span class="line">            queue.add(i);</span><br><span class="line">            System.out.println(<span class="string">&quot;塞入&quot;</span> + i);</span><br><span class="line">            <span class="keyword">try</span> &#123;</span><br><span class="line">                Thread.sleep(<span class="number">500</span>);</span><br><span class="line">            &#125; <span class="keyword">catch</span> (InterruptedException e) &#123;</span><br><span class="line">                e.printStackTrace();</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;);</span><br><span class="line">    <span class="type">Thread</span> <span class="variable">t2</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">Thread</span>(() -&gt; &#123;</span><br><span class="line">        <span class="keyword">for</span> (; ; ) &#123;</span><br><span class="line">            System.out.println(<span class="string">&quot;消费&quot;</span>+queue.take());</span><br><span class="line">            <span class="keyword">try</span> &#123;</span><br><span class="line">                Thread.sleep(<span class="number">800</span>);</span><br><span class="line">            &#125; <span class="keyword">catch</span> (InterruptedException e) &#123;</span><br><span class="line">                e.printStackTrace();</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">    &#125;);</span><br><span class="line">    t1.start();</span><br><span class="line">    t2.start();</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>





<h3 id="19、手写多线程交替打印ABC"><a href="#19、手写多线程交替打印ABC" class="headerlink" title="19、手写多线程交替打印ABC"></a><strong>19、手写多线程交替打印ABC</strong></h3><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">package</span> com.demo.test;</span><br><span class="line"><span class="keyword">import</span> java.util.concurrent.locks.Condition;</span><br><span class="line"><span class="keyword">import</span> java.util.concurrent.locks.ReentrantLock;</span><br><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">syncPrinter</span> <span class="keyword">implements</span> <span class="title class_">Runnable</span>&#123;</span><br><span class="line">    <span class="comment">// 打印次数</span></span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">static</span> <span class="keyword">final</span> <span class="type">int</span> <span class="variable">PRINT_COUNT</span> <span class="operator">=</span> <span class="number">10</span>;</span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">final</span> ReentrantLock reentrantLock;</span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">final</span> Condition thisCondtion;</span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">final</span> Condition nextCondtion;</span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">final</span> <span class="type">char</span> printChar;</span><br><span class="line">    <span class="keyword">public</span> <span class="title function_">syncPrinter</span><span class="params">(ReentrantLock reentrantLock, Condition thisCondtion, Condition nextCondition, <span class="type">char</span> printChar)</span> &#123;</span><br><span class="line">        <span class="built_in">this</span>.reentrantLock = reentrantLock;</span><br><span class="line">        <span class="built_in">this</span>.nextCondtion = nextCondition;</span><br><span class="line">        <span class="built_in">this</span>.thisCondtion = thisCondtion;</span><br><span class="line">        <span class="built_in">this</span>.printChar = printChar;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">run</span><span class="params">()</span> &#123;</span><br><span class="line">        <span class="comment">// 获取打印锁 进入临界区</span></span><br><span class="line">        reentrantLock.lock();</span><br><span class="line">        <span class="keyword">try</span> &#123;</span><br><span class="line">            <span class="comment">// 连续打印PRINT_COUNT次</span></span><br><span class="line">            <span class="keyword">for</span> (<span class="type">int</span> <span class="variable">i</span> <span class="operator">=</span> <span class="number">0</span>; i &lt; PRINT_COUNT; i++) &#123;</span><br><span class="line">                <span class="comment">//打印字符</span></span><br><span class="line">                System.out.print(printChar);</span><br><span class="line">                <span class="comment">// 使用nextCondition唤醒下一个线程</span></span><br><span class="line">                <span class="comment">// 因为只有一个线程在等待，所以signal或者signalAll都可以</span></span><br><span class="line">                nextCondtion.signal();</span><br><span class="line">                <span class="comment">// 不是最后一次则通过thisCondtion等待被唤醒</span></span><br><span class="line">                <span class="comment">// 必须要加判断，不然虽然能够打印10次，但10次后就会直接死锁</span></span><br><span class="line">                <span class="keyword">if</span> (i &lt; PRINT_COUNT - <span class="number">1</span>) &#123;</span><br><span class="line">                    <span class="keyword">try</span> &#123;</span><br><span class="line">                        <span class="comment">// 本线程让出锁并等待唤醒</span></span><br><span class="line">                        thisCondtion.await();</span><br><span class="line">                    &#125; <span class="keyword">catch</span> (InterruptedException e) &#123;</span><br><span class="line">                        e.printStackTrace();</span><br><span class="line">                    &#125;</span><br><span class="line">                &#125;</span><br><span class="line">            &#125;</span><br><span class="line">        &#125; <span class="keyword">finally</span> &#123;</span><br><span class="line">            reentrantLock.unlock();</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">    </span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title function_">main</span><span class="params">(String[] args)</span> <span class="keyword">throws</span> InterruptedException &#123;</span><br><span class="line">        <span class="type">ReentrantLock</span> <span class="variable">lock</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">ReentrantLock</span>();</span><br><span class="line">        <span class="type">Condition</span> <span class="variable">conditionA</span> <span class="operator">=</span> lock.newCondition();</span><br><span class="line">        <span class="type">Condition</span> <span class="variable">conditionB</span> <span class="operator">=</span> lock.newCondition();</span><br><span class="line">        <span class="type">Condition</span> <span class="variable">conditionC</span> <span class="operator">=</span> lock.newCondition();</span><br><span class="line">        <span class="type">Thread</span> <span class="variable">printA</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">Thread</span>(<span class="keyword">new</span> <span class="title class_">syncPrinter</span>(lock, conditionA, conditionB,<span class="string">&#x27;A&#x27;</span>));</span><br><span class="line">        <span class="type">Thread</span> <span class="variable">printB</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">Thread</span>(<span class="keyword">new</span> <span class="title class_">syncPrinter</span>(lock, conditionB, conditionC,<span class="string">&#x27;B&#x27;</span>));</span><br><span class="line">        <span class="type">Thread</span> <span class="variable">printC</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">Thread</span>(<span class="keyword">new</span> <span class="title class_">syncPrinter</span>(lock, conditionC, conditionA,<span class="string">&#x27;C&#x27;</span>));</span><br><span class="line">        printA.start();</span><br><span class="line">        Thread.sleep(<span class="number">100</span>);</span><br><span class="line">        printB.start();</span><br><span class="line">        Thread.sleep(<span class="number">100</span>);</span><br><span class="line">        printC.start();</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>



<h3 id="20、交替打印FooBar"><a href="#20、交替打印FooBar" class="headerlink" title="20、交替打印FooBar"></a>20、交替打印FooBar</h3><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br><span class="line">86</span><br><span class="line">87</span><br><span class="line">88</span><br><span class="line">89</span><br><span class="line">90</span><br><span class="line">91</span><br><span class="line">92</span><br><span class="line">93</span><br><span class="line">94</span><br><span class="line">95</span><br><span class="line">96</span><br><span class="line">97</span><br><span class="line">98</span><br><span class="line">99</span><br><span class="line">100</span><br><span class="line">101</span><br><span class="line">102</span><br><span class="line">103</span><br><span class="line">104</span><br><span class="line">105</span><br><span class="line">106</span><br><span class="line">107</span><br><span class="line">108</span><br><span class="line">109</span><br><span class="line">110</span><br><span class="line">111</span><br><span class="line">112</span><br><span class="line">113</span><br><span class="line">114</span><br><span class="line">115</span><br><span class="line">116</span><br><span class="line">117</span><br><span class="line">118</span><br><span class="line">119</span><br><span class="line">120</span><br><span class="line">121</span><br><span class="line">122</span><br><span class="line">123</span><br><span class="line">124</span><br><span class="line">125</span><br><span class="line">126</span><br><span class="line">127</span><br><span class="line">128</span><br><span class="line">129</span><br><span class="line">130</span><br><span class="line">131</span><br><span class="line">132</span><br><span class="line">133</span><br><span class="line">134</span><br><span class="line">135</span><br><span class="line">136</span><br><span class="line">137</span><br><span class="line">138</span><br><span class="line">139</span><br><span class="line">140</span><br><span class="line">141</span><br><span class="line">142</span><br><span class="line">143</span><br><span class="line">144</span><br><span class="line">145</span><br><span class="line">146</span><br><span class="line">147</span><br><span class="line">148</span><br><span class="line">149</span><br><span class="line">150</span><br><span class="line">151</span><br><span class="line">152</span><br><span class="line">153</span><br><span class="line">154</span><br><span class="line">155</span><br><span class="line">156</span><br><span class="line">157</span><br><span class="line">158</span><br><span class="line">159</span><br><span class="line">160</span><br><span class="line">161</span><br><span class="line">162</span><br><span class="line">163</span><br><span class="line">164</span><br><span class="line">165</span><br><span class="line">166</span><br><span class="line">167</span><br><span class="line">168</span><br><span class="line">169</span><br><span class="line">170</span><br><span class="line">171</span><br><span class="line">172</span><br><span class="line">173</span><br><span class="line">174</span><br><span class="line">175</span><br><span class="line">176</span><br><span class="line">177</span><br><span class="line">178</span><br><span class="line">179</span><br><span class="line">180</span><br><span class="line">181</span><br><span class="line">182</span><br><span class="line">183</span><br><span class="line">184</span><br><span class="line">185</span><br><span class="line">186</span><br><span class="line">187</span><br><span class="line">188</span><br><span class="line">189</span><br><span class="line">190</span><br><span class="line">191</span><br><span class="line">192</span><br><span class="line">193</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//手太阴肺经 BLOCKING Queue</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">FooBar</span> &#123;</span><br><span class="line">    <span class="keyword">private</span> <span class="type">int</span> n;</span><br><span class="line">    <span class="keyword">private</span> BlockingQueue&lt;Integer&gt; bar = <span class="keyword">new</span> <span class="title class_">LinkedBlockingQueue</span>&lt;&gt;(<span class="number">1</span>);</span><br><span class="line">    <span class="keyword">private</span> BlockingQueue&lt;Integer&gt; foo = <span class="keyword">new</span> <span class="title class_">LinkedBlockingQueue</span>&lt;&gt;(<span class="number">1</span>);</span><br><span class="line">    <span class="keyword">public</span> <span class="title function_">FooBar</span><span class="params">(<span class="type">int</span> n)</span> &#123;</span><br><span class="line">        <span class="built_in">this</span>.n = n;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">foo</span><span class="params">(Runnable printFoo)</span> <span class="keyword">throws</span> InterruptedException &#123;</span><br><span class="line">        <span class="keyword">for</span> (<span class="type">int</span> <span class="variable">i</span> <span class="operator">=</span> <span class="number">0</span>; i &lt; n; i++) &#123;</span><br><span class="line">            foo.put(i);</span><br><span class="line">            printFoo.run();</span><br><span class="line">            bar.put(i);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">bar</span><span class="params">(Runnable printBar)</span> <span class="keyword">throws</span> InterruptedException &#123;</span><br><span class="line">        <span class="keyword">for</span> (<span class="type">int</span> <span class="variable">i</span> <span class="operator">=</span> <span class="number">0</span>; i &lt; n; i++) &#123;</span><br><span class="line">            bar.take();</span><br><span class="line">            printBar.run();</span><br><span class="line">            foo.take();</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">//手阳明大肠经CyclicBarrier 控制先后</span></span><br><span class="line"><span class="keyword">class</span> <span class="title class_">FooBar6</span> &#123;</span><br><span class="line">    <span class="keyword">private</span> <span class="type">int</span> n;</span><br><span class="line">    <span class="keyword">public</span> <span class="title function_">FooBar6</span><span class="params">(<span class="type">int</span> n)</span> &#123;</span><br><span class="line">        <span class="built_in">this</span>.n = n;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="type">CyclicBarrier</span> <span class="variable">cb</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">CyclicBarrier</span>(<span class="number">2</span>);</span><br><span class="line">    <span class="keyword">volatile</span> <span class="type">boolean</span> <span class="variable">fin</span> <span class="operator">=</span> <span class="literal">true</span>;</span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">foo</span><span class="params">(Runnable printFoo)</span> <span class="keyword">throws</span> InterruptedException &#123;</span><br><span class="line">        <span class="keyword">for</span> (<span class="type">int</span> <span class="variable">i</span> <span class="operator">=</span> <span class="number">0</span>; i &lt; n; i++) &#123;</span><br><span class="line">            <span class="keyword">while</span>(!fin);</span><br><span class="line">            printFoo.run();</span><br><span class="line">            fin = <span class="literal">false</span>;</span><br><span class="line">            <span class="keyword">try</span> &#123;</span><br><span class="line">                cb.await();</span><br><span class="line">            &#125; <span class="keyword">catch</span> (BrokenBarrierException e) &#123;&#125;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">bar</span><span class="params">(Runnable printBar)</span> <span class="keyword">throws</span> InterruptedException &#123;</span><br><span class="line">        <span class="keyword">for</span> (<span class="type">int</span> <span class="variable">i</span> <span class="operator">=</span> <span class="number">0</span>; i &lt; n; i++) &#123;</span><br><span class="line">            <span class="keyword">try</span> &#123;</span><br><span class="line">                cb.await();</span><br><span class="line">            &#125; <span class="keyword">catch</span> (BrokenBarrierException e) &#123;&#125;</span><br><span class="line">            printBar.run();</span><br><span class="line">            fin = <span class="literal">true</span>;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">//手少阴心经 自旋 + 让出CPU</span></span><br><span class="line"><span class="keyword">class</span> <span class="title class_">FooBar5</span> &#123;</span><br><span class="line">    <span class="keyword">private</span> <span class="type">int</span> n;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> <span class="title function_">FooBar5</span><span class="params">(<span class="type">int</span> n)</span> &#123;</span><br><span class="line">        <span class="built_in">this</span>.n = n;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">volatile</span> <span class="type">boolean</span> <span class="variable">permitFoo</span> <span class="operator">=</span> <span class="literal">true</span>;</span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">foo</span><span class="params">(Runnable printFoo)</span> <span class="keyword">throws</span> InterruptedException &#123;     </span><br><span class="line">        <span class="keyword">for</span> (<span class="type">int</span> <span class="variable">i</span> <span class="operator">=</span> <span class="number">0</span>; i &lt; n; ) &#123;</span><br><span class="line">            <span class="keyword">if</span>(permitFoo) &#123;</span><br><span class="line">        	    printFoo.run();</span><br><span class="line">            	i++;</span><br><span class="line">            	permitFoo = <span class="literal">false</span>;</span><br><span class="line">            &#125;<span class="keyword">else</span>&#123;</span><br><span class="line">                Thread.yield();</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">bar</span><span class="params">(Runnable printBar)</span> <span class="keyword">throws</span> InterruptedException &#123;       </span><br><span class="line">        <span class="keyword">for</span> (<span class="type">int</span> <span class="variable">i</span> <span class="operator">=</span> <span class="number">0</span>; i &lt; n; ) &#123;</span><br><span class="line">            <span class="keyword">if</span>(!permitFoo) &#123;</span><br><span class="line">        	printBar.run();</span><br><span class="line">        	i++;</span><br><span class="line">        	permitFoo = <span class="literal">true</span>;</span><br><span class="line">            &#125;<span class="keyword">else</span>&#123;</span><br><span class="line">                Thread.yield();</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="comment">//手少阳三焦经 可重入锁 + Condition</span></span><br><span class="line"><span class="keyword">class</span> <span class="title class_">FooBar4</span> &#123;</span><br><span class="line">    <span class="keyword">private</span> <span class="type">int</span> n;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> <span class="title function_">FooBar4</span><span class="params">(<span class="type">int</span> n)</span> &#123;</span><br><span class="line">        <span class="built_in">this</span>.n = n;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="type">Lock</span> <span class="variable">lock</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">ReentrantLock</span>(<span class="literal">true</span>);</span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">final</span> <span class="type">Condition</span> <span class="variable">foo</span> <span class="operator">=</span> lock.newCondition();</span><br><span class="line">    <span class="keyword">volatile</span> <span class="type">boolean</span> <span class="variable">flag</span> <span class="operator">=</span> <span class="literal">true</span>;</span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">foo</span><span class="params">(Runnable printFoo)</span> <span class="keyword">throws</span> InterruptedException &#123;</span><br><span class="line">        <span class="keyword">for</span> (<span class="type">int</span> <span class="variable">i</span> <span class="operator">=</span> <span class="number">0</span>; i &lt; n; i++) &#123;</span><br><span class="line">            lock.lock();</span><br><span class="line">            <span class="keyword">try</span> &#123;</span><br><span class="line">            	<span class="keyword">while</span>(!flag) &#123;</span><br><span class="line">                    foo.await();</span><br><span class="line">                &#125;</span><br><span class="line">                printFoo.run();</span><br><span class="line">                flag = <span class="literal">false</span>;</span><br><span class="line">                foo.signal();</span><br><span class="line">            &#125;<span class="keyword">finally</span> &#123;</span><br><span class="line">            	lock.unlock();</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">bar</span><span class="params">(Runnable printBar)</span> <span class="keyword">throws</span> InterruptedException &#123;</span><br><span class="line">        <span class="keyword">for</span> (<span class="type">int</span> <span class="variable">i</span> <span class="operator">=</span> <span class="number">0</span>; i &lt; n;i++) &#123;</span><br><span class="line">            lock.lock();</span><br><span class="line">            <span class="keyword">try</span> &#123;</span><br><span class="line">            	<span class="keyword">while</span>(flag) &#123;</span><br><span class="line">                    foo.await();</span><br><span class="line">            	&#125;</span><br><span class="line">                printBar.run();</span><br><span class="line">                flag = <span class="literal">true</span>;</span><br><span class="line">                foo.signal();</span><br><span class="line">            &#125;<span class="keyword">finally</span> &#123;</span><br><span class="line">            	lock.unlock();</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">//手厥阴心包经 synchronized + 标志位 + 唤醒</span></span><br><span class="line"><span class="keyword">class</span> <span class="title class_">FooBar3</span> &#123;</span><br><span class="line">    <span class="keyword">private</span> <span class="type">int</span> n;</span><br><span class="line">    <span class="comment">// 标志位，控制执行顺序，true执行printFoo，false执行printBar</span></span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">volatile</span> <span class="type">boolean</span> <span class="variable">type</span> <span class="operator">=</span> <span class="literal">true</span>;</span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">final</span> Object foo=  <span class="keyword">new</span> <span class="title class_">Object</span>(); <span class="comment">// 锁标志</span></span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> <span class="title function_">FooBar3</span><span class="params">(<span class="type">int</span> n)</span> &#123;</span><br><span class="line">        <span class="built_in">this</span>.n = n;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">foo</span><span class="params">(Runnable printFoo)</span> <span class="keyword">throws</span> InterruptedException &#123;</span><br><span class="line">        <span class="keyword">for</span> (<span class="type">int</span> <span class="variable">i</span> <span class="operator">=</span> <span class="number">0</span>; i &lt; n; i++) &#123;</span><br><span class="line">            <span class="keyword">synchronized</span> (foo) &#123;</span><br><span class="line">                <span class="keyword">while</span>(!type)&#123;</span><br><span class="line">                    foo.wait();</span><br><span class="line">                &#125;</span><br><span class="line">                printFoo.run();</span><br><span class="line">                type = <span class="literal">false</span>;</span><br><span class="line">                foo.notifyAll();</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">bar</span><span class="params">(Runnable printBar)</span> <span class="keyword">throws</span> InterruptedException &#123;</span><br><span class="line">        <span class="keyword">for</span> (<span class="type">int</span> <span class="variable">i</span> <span class="operator">=</span> <span class="number">0</span>; i &lt; n; i++) &#123;</span><br><span class="line">            <span class="keyword">synchronized</span> (foo) &#123;</span><br><span class="line">                <span class="keyword">while</span>(type)&#123;</span><br><span class="line">                    foo.wait();</span><br><span class="line">                &#125;</span><br><span class="line">                printBar.run();</span><br><span class="line">                type = <span class="literal">true</span>;</span><br><span class="line">                foo.notifyAll();</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="comment">//手太阳小肠经 信号量 适合控制顺序</span></span><br><span class="line"><span class="keyword">class</span> <span class="title class_">FooBar2</span> &#123;</span><br><span class="line">    <span class="keyword">private</span> <span class="type">int</span> n;</span><br><span class="line">    <span class="keyword">private</span> <span class="type">Semaphore</span> <span class="variable">foo</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">Semaphore</span>(<span class="number">1</span>);</span><br><span class="line">    <span class="keyword">private</span> <span class="type">Semaphore</span> <span class="variable">bar</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">Semaphore</span>(<span class="number">0</span>);</span><br><span class="line">    <span class="keyword">public</span> <span class="title function_">FooBar2</span><span class="params">(<span class="type">int</span> n)</span> &#123;</span><br><span class="line">        <span class="built_in">this</span>.n = n;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">foo</span><span class="params">(Runnable printFoo)</span> <span class="keyword">throws</span> InterruptedException &#123;</span><br><span class="line">        <span class="keyword">for</span> (<span class="type">int</span> <span class="variable">i</span> <span class="operator">=</span> <span class="number">0</span>; i &lt; n; i++) &#123;</span><br><span class="line">            foo.acquire();</span><br><span class="line">        	printFoo.run();</span><br><span class="line">            bar.release();</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">bar</span><span class="params">(Runnable printBar)</span> <span class="keyword">throws</span> InterruptedException &#123;</span><br><span class="line">        <span class="keyword">for</span> (<span class="type">int</span> <span class="variable">i</span> <span class="operator">=</span> <span class="number">0</span>; i &lt; n; i++) &#123;</span><br><span class="line">            bar.acquire();</span><br><span class="line">        	printBar.run();</span><br><span class="line">            foo.release();</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br></pre></td></tr></table></figure>









<h1 id="六、个人项目"><a href="#六、个人项目" class="headerlink" title="六、个人项目"></a><strong>六、个人项目</strong></h1><h2 id="一、一站到底"><a href="#一、一站到底" class="headerlink" title="一、一站到底"></a><strong>一、一站到底</strong></h2><p>​	采用SpringBoot构建项目，主要通过分布式缓存、队列、限流保证系统高可用，Netty、缓存、反向代理保证高并发。</p>
<blockquote>
<p>双人对战答题、公司对战抢答</p>
</blockquote>
<h3 id="1、如何设计排行榜"><a href="#1、如何设计排行榜" class="headerlink" title="1、如何设计排行榜"></a>1、如何设计排行榜</h3><ul>
<li>个人总得分和总排名实时更新</li>
<li>个人排行榜按分数、时间、次数、正确率展示</li>
<li>日榜、过去N日榜滚动更新</li>
</ul>
<h4 id="性能优化过程"><a href="#性能优化过程" class="headerlink" title="性能优化过程"></a>性能优化过程</h4><p>​	第一条需求很简单，使用了Redis的<strong>Zset</strong>实现不过这里总得分采用了基于<strong>分数、时间、次数和正确率</strong>的混合加权。考虑到数据的<strong>持久化</strong>，以及<strong>关系数据库和缓存的一致性</strong>导致的设计的复杂性，使用了<strong>谷歌</strong>开源的<strong>JamsRanking</strong></p>
<p>​	优点<strong>是可以直接使用现成的setScores和getRanking接口封装了Redis和Mysql和消息队列的完成</strong>事务和一致性<strong>的使用细节。缺点是</strong>并发比较低<strong>使用Jmeter进行压测，单机只有</strong>20<strong>左右的</strong>TPS**</p>
<p>​	后来看了下源码，主要是它针对每一次设置都进行了分布式事务处理，并且会返回事务提交或回滚的结果。了解了底层实现以后就去谷歌的<strong>开源社区</strong>去查阅了相关的解决方案，当时官方对这个问题并没有通过<strong>配置能直接解决问题</strong>的快捷方式，不过推荐了使用者自身如果对响应时间不高的场景下可以采用<strong>批量合并事务</strong>的方式进行优化。基于这个思路，我们把写操作进行了封装并放入了<strong>队列</strong>，然后在消费者端批量取得数据后进行事务的批量处理，压测环境下整体性能达到了<strong>500TPS</strong>。已经基本满足了线上更新的需求，但是当时压测的过程中，队列偶尔的吞吐量会<strong>大范围波动</strong>，经常会持续数十秒，然后业务一次性处理完再响应，导致<strong>局部响应时间大幅度增长</strong></p>
<p>​	后来也是在官网上查询，了解到谷歌开源组件使用的<strong>队列服务</strong>底层是使用<strong>BigTable</strong>作为持久层，但是当BigTable分片过大时，会触发<strong>再分片</strong>的过程，再分片的过程中，是<strong>不会进行任务分发</strong>的，所以就会导致先前的问题。针对这个问题，谷歌官方的建议是提前<strong>配置队列的数量、负载策略和最大容量</strong>等信息，保证所有队列<strong>不同时触发</strong>再分片</p>
<p>​	进行两次优化后，压测环境已经基本可以满足预期了，在实际生产环境的部署中，发现对于事务更新失败时，JamsRanking会对失败的事务进行<strong>切分和重试</strong>，整个过程对于研发人员是<strong>透明</strong>的，不利于线上问题排查，所以我们当时特地写了一个watchdog的工具，监控事务回滚达到十次以上的事务，查明原因后通过后台管理系统进行相应补偿，保证<strong>最终一致性</strong></p>
<p><strong>最终结果：</strong></p>
<ul>
<li><p>高效快速：能在数百毫秒内找到玩家排名以及进行更新</p>
</li>
<li><p>强一致性以及持久化、排名准确</p>
</li>
<li><p>可以扩展到任意数量的玩家</p>
</li>
<li><p>吞吐量有限制，只能支持约每秒 500次更新。</p>
</li>
</ul>
<p>针对这个缺点谷歌官方也是给出了使用分片树和近似排名的解决方案，当然复杂的方案有更高的运维成本，所以我们优化工作也就到此为止</p>
<h4 id="方案优化过程"><a href="#方案优化过程" class="headerlink" title="方案优化过程"></a>方案优化过程</h4><h4 id="方案1：每日一个滚动榜，当日汇聚（费时间）"><a href="#方案1：每日一个滚动榜，当日汇聚（费时间）" class="headerlink" title="方案1：每日一个滚动榜，当日汇聚（费时间）"></a>方案1：每日一个滚动榜，当日汇聚（费时间）</h4><p>​	首先记录每天的排行榜和一个滚动榜，加分时同时写入这两个榜单，每日零点后跑工具将前几天数据累加写入当日滚动榜，该方案缺点是时间复杂度高，7天榜还好，只需要读过去6天数据，如果是100天榜，该方案需要读过去99天榜，显然不可接受</p>
<h4 id="方案2：全局N个滚动榜同时写（费空间）"><a href="#方案2：全局N个滚动榜同时写（费空间）" class="headerlink" title="方案2：全局N个滚动榜同时写（费空间）"></a>方案2：全局N个滚动榜同时写（费空间）</h4><p>​	要做到每日零点后榜单实时生效，而不需要等待离线作业的完成，一种方案是预写未来的榜单。可以写当天的滚动榜的同时，写往后N-1天的滚动榜一起写入该方案不仅能脱离离线作业做到实时更新，且可以省略每天的日榜。但缺点也不难看出，对于7天滚动榜，每次写操作需要更新7个榜单，但是对于百日榜，空间消耗无法接受，1000万榜单大约消耗1G内存</p>
<h4 id="方案3：实时更新，常数次写操作"><a href="#方案3：实时更新，常数次写操作" class="headerlink" title="方案3：实时更新，常数次写操作"></a>方案3：实时更新，常数次写操作</h4><p>有不有办法做到既能实时更新，写榜数量也不随N的增加而增加呢？</p>
<p>​	仍然是记录每天的排行榜和一个滚动榜，加分操作也还是同时操作当日榜和全局榜，但每日零点的离线作业改为从全局榜中减去之前过期的数据，从而实现先滚动更新。  此方案每次只需读取一个日榜做减法，时间复杂度为O(1)；但是无法做到实时更新。 这个方案的优点是在十二点前提前准备好差分榜，到了十二点直接加上当天数据就是滚动榜内容 ，这样就在常数次写操作的前提下，实现了滚动榜的实时更新</p>
<h3 id="2、如何解决重复答题"><a href="#2、如何解决重复答题" class="headerlink" title="2、如何解决重复答题"></a>2、<strong>如何解决重复答题</strong></h3><p>​	<strong>利用setnx防止重复答题</strong><br>​	分布式锁是控制分布式系统之间同步访问共享资源的一种方式。 利用Redis的单线程特性对共享资源进行串行化处理</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 获取锁推荐使用set的方式</span></span><br><span class="line"><span class="type">String</span> <span class="variable">result</span> <span class="operator">=</span> jedis.set(lockKey, requestId, <span class="string">&quot;NX&quot;</span>, <span class="string">&quot;EX&quot;</span>, expireTime);</span><br></pre></td></tr></table></figure>

<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 推荐使用redis+lua脚本</span></span><br><span class="line"><span class="type">String</span> <span class="variable">lua</span> <span class="operator">=</span> <span class="string">&quot;if redis.call(&#x27;get&#x27;,KEYS[1]) == ARGV[1] then return redis.call(&#x27;del&#x27;,KEYS[1]) else return 0 end&quot;</span>;</span><br><span class="line"><span class="type">Object</span> <span class="variable">result</span> <span class="operator">=</span> jedis.eval(lua, Collections.singletonList(lockKey)</span><br></pre></td></tr></table></figure>



<h3 id="3、一个题目被多个人抢答"><a href="#3、一个题目被多个人抢答" class="headerlink" title="3、一个题目被多个人抢答"></a><strong>3、一个题目被多个人抢答</strong></h3><p>​	<strong>利用redis来实现乐观锁（抢答）</strong>，好处是答错的人不影响状态，第一个秒杀答对的人才能得分。</p>
<p>1、利用redis的watch功能，监控这个 Corp:Activ:Qust: 的状态值<br>2、获取Corp:Activ:Qust: 的值，创建redis事务，给这个key的值-1<br>3、执行这个事务，如果key的值被修改过则回滚，key不变</p>
<h3 id="4、如何管理昵称重复"><a href="#4、如何管理昵称重复" class="headerlink" title="4、如何管理昵称重复"></a><strong>4、如何管理昵称重复</strong></h3><p>​	<strong>使用布隆过滤器：</strong></p>
<p>​	它实际上是一个很长的二进制矢量数组和 K 个哈希函数。当一个昵称加入布隆过滤器中的时候，会进行如下操作：</p>
<ul>
<li>使用 K 个哈希函数对元素值进行 K 次计算，得到 K 个哈希值。</li>
<li>根据得到的哈希值，在位数组中把对应下标的值置为 1。 Na</li>
</ul>
<p>​	用户新增昵称时需要首先计算K个哈希值，如果K个哈希值有一个不为0则通过，否则不通过，不通过时通过加随机字符串再次检验，检测通过后返回给前端，帮助用户自动填写。</p>
<p>​	布隆过滤器的好处是它<strong>可以用来判断一个元素是否在一个集合中</strong>。它的优势是只需要占用很小的内存空间以及有着高效的查询效率。对于布隆过滤器而言，它的本质是一个<strong>位数组</strong>：位数组就是数组的每个元素都只占用 1 bit ，并且每个元素只能是 0 或者 1。</p>
<p>BloomFilter 的优势是，全内存操作，性能很高。另外空间效率非常高，<strong>要达到 1% 的误判率，平均单条记录占用 1.2 字节即可。而且，平均单条记录每增加 0.6 字节，还可让误判率继续变为之前的 1&#x2F;10，即平均单条记录占用 1.8 字节，误判率可以达到 1&#x2F;1000；平均单条记录占用 2.4 字节，误判率可以到 1&#x2F;10000，以此类推</strong>。这里的误判率是指，BloomFilter 判断某个 key 存在，但它实际不存在的概率，因为它存的是 key 的 Hash 值，而非 key 的值，所以有概率存在这样的 key，它们内容不同，但多次 Hash 后的 Hash 值都相同。对于 BloomFilter 判断不存在的 key ，则是 100% 不存在的，反证法，如果这个 key 存在，那它每次 Hash 后对应的 Hash 值位置肯定是 1，而不会是 0</p>
<p>​		</p>
<h3 id="5、如何管理出题定时任务"><a href="#5、如何管理出题定时任务" class="headerlink" title="5、如何管理出题定时任务"></a><strong>5、如何管理出题定时任务</strong></h3><p>​	压测环境中服务器通过Netty的主从Reactor多路复用NIO事件模型，单机可以<strong>轻松应对十万长连接</strong>，但是每个业务中，由于每个用户登录系统后需要按照指定顺序答题，例如一共要答十道，那么服务器针对这一个用户就会产生十个定时任务，所以对于系统来说，定时器的<strong>数量就是百万级别的</strong>。</p>
<p>​	通过压测结果发现：JDK自带的Timer，在大概三万并发时性能就急剧下降了。也是此时根据业务场景的需要，将定时任务改成了Netty自带的HashedWheelTimer时间轮方案，通过压测单机在50万级别下依然能够平滑的执行。</p>
<p>​	也是这个强烈的反差，使我在强烈的好奇心促使下，阅读源码了解到常规的JDK 的Timer 和 DelayedQueue 等工具类，可实现简单的定时任务，单底层用的是<strong>堆数据结构</strong>，存取复杂度都是 <strong>O(NlogN)<strong>，无法支撑海量定时任务。</strong>Netty经典的时间轮方案</strong>，正是通过将任务存取及取消操作时间复杂度降为 O(1)，而广泛应用在定时<strong>任务量大、性能要求高</strong>的场景中。</p>
<p>​	<img src="https://tva1.sinaimg.cn/large/0081Kckwly1glvl9c3hp2j30py0d7q4i.jpg" alt="img" style="zoom:50%;" /></p>
<p>​	基于Netty的Websocket底层，服务器端维护一个高效批量管理定时任务的调度模型。时间轮一般会实现成一个<strong>环形数组结构</strong>，类似一个时钟，分为很多槽，一个槽代表一个时间间隔，每个槽使用<strong>双向链表</strong>存储定时任务。指针<strong>周期性地跳动</strong>，跳动到一个槽位，就执行该槽位的定时任务。</p>
<p>​	单层时间轮的容量和精度都是有限的，对于精度要求特别高、时间跨度特别大或是海量定时任务需要调度的场景，可以考虑使用多级时间轮以及持久化存储与时间轮结合的方案。时间轮的<strong>定时任务处理逻辑</strong>如下：</p>
<ol>
<li>将缓存在 timeouts 队列中的定时任务转移到时间轮中对应的槽中</li>
<li>根据当前指针定位对应槽，处理该槽位的双向链表中的定时任务，从链表头部开始迭代：<ul>
<li>属于当前时钟周期则取出运行</li>
<li>不属于则将其剩余的时钟周期数减一</li>
</ul>
</li>
<li>检测时间轮的状态。如果时间轮处于运行状态，则循环执行上述步骤，不断执行定时任务。</li>
</ol>
<h3 id="6：如何解决客户端断连"><a href="#6：如何解决客户端断连" class="headerlink" title="6：如何解决客户端断连"></a><strong>6：如何解决客户端断连</strong></h3><p>​	使用Netty的<strong>重连检测狗</strong>ConnectionWatchdog</p>
<p>​	服务端定义refreshTime，当我们从channel中read到了服务端发来的心跳响应消息的话，就刷新refreshTime为当前时间</p>
<p>​	客户端在state是WRITER_IDLE的时候每隔一秒就发送一个心跳包到sever端，告诉server端我还活着。</p>
<p>当重连成功时，会触发channelActive方法，在这里我们开启了一个定时任务去判断refreshTime和当前时间的时间差，超过5秒说明断线了，要进行重连，最后计算重连次数，尝试连接2次以上连不上就会修改header信息强制重连去连另一个服务器。</p>
<h2 id="二、秒杀项目"><a href="#二、秒杀项目" class="headerlink" title="二、秒杀项目"></a>二、秒杀项目</h2><h3 id="技术选型"><a href="#技术选型" class="headerlink" title="技术选型"></a><strong>技术选型</strong></h3><p>秒杀用到的基础组件，主要有<strong>框架、KV 存储、关系型数据库、MQ</strong>。</p>
<p>框架主要有 Web 框架和 RPC 框架。</p>
<p>其中，Web 框架主要用于提供 HTTP 接口给浏览器访问，所以 Web 框架的选型在秒杀服务中非常重要。在这里，我<strong>推荐Gin</strong>，它的性能和易用性都不错，在 <strong>GitHub 上的 Star 达到了 44k</strong>。对比性能最好的 fasthttp，虽然 fasthttp 在请求延迟低于 10ms 时性能优势明显，但其底层使用的对象池容易让人踩坑，导致其易用性较差，所以没必要过于追求性能而忽略了稳定性</p>
<p>至于 RPC 框架，我推荐选用 <strong>gRPC</strong>，因为它的扩展性和性能都非常不错。在秒杀系统中，Redis 中的数据主要是给秒杀接口服务使用，以便将配置从管理后台同步到 Redis 缓存中。</p>
<p>KV 存储方面，秒杀系统中主要是用 <strong>Redis 缓存活动配置</strong>，用 <strong>etcd 存储集群信息</strong>。</p>
<p>关系型数据库中，<strong>MySQL</strong> 技术成熟且稳定可靠，秒杀系统用它存储活动配置数据很合适。主要 原因还是秒杀活动信息和库存数据都缓存在 Redis 中，活动过程中秒杀服务不操作数据库， 使用 MySQL 完全能够满足需求。</p>
<p>MQ 有很多种，其中 <strong>Kafka</strong> 在业界认可度最高，技术也非常成熟，性能很不错，非常适合用在秒杀系统中。Kafka 支持自动创建队列，秒杀服务各个节点可以用它自动创建属于自己的队列</p>
<h3 id="方案设计"><a href="#方案设计" class="headerlink" title="方案设计"></a>方案设计</h3><p><strong>背景</strong></p>
<ul>
<li><p>秒杀业务简单，每个秒杀活动的商品是事先定义好的，商品有明确的类型和数量，卖完即止</p>
</li>
<li><p>秒杀活动定时上架，消费者可以在活动开始后，通过秒杀入口进行抢购秒杀活动</p>
</li>
<li><p>秒杀活动由于商品物美价廉，开始售卖后，会被快速抢购一空。</p>
</li>
</ul>
<p><strong>现象</strong></p>
<p>-<br>  秒杀活动持续时间短，访问冲击量大，秒杀系统需要应对这种爆发性的访问模型</p>
<p>-<br>  业务的请求量远远大于售卖量，大部分是陪跑的请求，秒杀系统需要提前规划好处理策略</p>
<p>-<br>  前端访问量巨大，系统对后端数据的访问量也会短时间爆增，对数据存储资源进行良好设计</p>
<p>-<br>  活动期间会给整个业务系统带来超大负荷，需要制定各种策略，避免系统过载而宕机</p>
<p>-<br>  售卖活动商品价格低廉，存在套利空间，各种非法作弊手段层出，需要提前规划预防策略</p>
<p><strong>秒杀系统设计</strong></p>
<p>​	首先，要<strong>尽力将请求拦截在系统上游</strong>，层层设阻拦截，过滤掉无效或超量的请求。因为访问量远远大于商品数量，所有的请求打到后端服务的最后一步，其实并没有必要，反而会严重拖慢真正能成交的请求，降低用户体验。</p>
<p>​	秒杀系统专为秒杀活动服务，售卖商品确定，因此可以在设计秒杀商品页面时，将商品信息提前设计为静态信息，将静态的商品信息以及常规的 CSS、JS、宣传图片等静态资源，一起<strong>独立存放到 CDN 节点</strong>，加速访问，且降低系统访问压力，在访问前端也可以<strong>制定种种限制策略，</strong>比如活动没开始时，抢购按钮置灰，避免抢先访问，用户抢购一次后，也将按钮置灰，让用户排队等待，避免反复刷新。</p>
<p>​	其次，要<strong>充分利用缓存</strong>，提升系统的性能和可用性。</p>
<p>​	用户所有的请求进入秒杀系统前，通过<strong>负载均衡策略</strong>均匀分发到不同 Web 服务器，避免节点过载。在 Web 服务器中，首先检查用户的访问权限，识别并发刷订单的行为。如果发现售出数量已经达到秒杀数量，则直接返回结束，要将秒杀业务系统和其他业务系统进行功能分拆，尽量将秒杀系统及依赖服务<strong>独立分拆部署</strong>，避免影响其他核心业务系统。</p>
<p>​	秒杀系统需要构建访问记录缓存，记录访问 IP、用户的访问行为，发现异常访问，提前进行阻断及返回。同时还需要<strong>构建用户缓存</strong>，并针对历史数据分析，提前缓存僵尸强刷专业户，方便在秒杀期间对其进行策略限制。这些访问记录、用户数据，通过缓存进行存储，可以加速访问，另外，对用户数据还进行缓存预热，避免活动期间大量穿透。</p>
<h3 id="1、如何解决超卖？"><a href="#1、如何解决超卖？" class="headerlink" title="1、如何解决超卖？"></a><strong>1、如何解决超卖？</strong></h3><p>mysql乐观锁+redis预减库存+redis缓存卖完标记 </p>
<p>第一是基于<strong>数据库乐观锁</strong>的方式保证数据并发扣减的强一致性；</p>
<p>第二是基于<strong>数据库的事务</strong>实现批量扣减部分失败时的数据回滚。</p>
<p>​	在扣减指定数量前应先做一次前置数量校验的读请求（参考<strong>读写分离</strong> + <strong>全缓存方案</strong>）</p>
<blockquote>
<p>纯数据库乐观锁+事务的方式性能比较差，但是如果不计成本和考虑场景的话也完全够用，因为任何没有机器配置的指标，都是耍流氓。如果我采用 Oracle 的数据库、100 多核的刀锋服务器、SSD 的硬盘，即使是纯数据库的扣减方案，也是可以达到单机上万的 TPS 的。</p>
</blockquote>
<p><strong>单线程Redis 的 lua 脚本实现批量扣减</strong></p>
<p>当用户调用扣减接口时，将扣减的 对应数量 + 脚本标示传递至 Redis 即可，所有的扣减判断逻辑均在 Redis 中的 lua 脚本中执行，lua 脚本执行完成之后返还是否成功给客户端。</p>
<img src="https://tva1.sinaimg.cn/large/008i3skNly1gq6j9dkq6vj30w20kowku.jpg" alt="image-20210504174103769" style="zoom:50%;" />

<p>Redis 中的 lua 脚本执行时，首先会使用 get 命令查询 uuid 进行查重。当防重通过后，会<strong>批量获取对应的剩余库存状态并进行判断</strong>，如果一个扣减的数量大于剩余数量，则返回错误并提示数量不足。</p>
<p>Redis 的单线程模型，确保<strong>不会出现当所有扣减数量在判断均满足后，在实际扣减时却数量不够</strong>。同时，单线程保证判断数量的步骤和后续扣减步骤之间，没有其他任何线程出现并发的执行。</p>
<p>当 Redis 扣减成功后，扣减接口会<strong>异步的将此次扣减内容保存至数据库</strong>。异步保存数据库的目的是防止出现极端情况—— Redis 宕机后数据未持久化到磁盘，此时我们可以使用数据库恢复或者校准数据</p>
<p>最后，运营后台直连数据库，是运营和商家修改库存的入口。商家在运营后台进货物进行补充。同时，运营后台的实现需要将此数量<strong>同步的增加至 Redis</strong>，因为当前方案的所有实际扣减都在 Redis 中</p>
<blockquote>
<p>纯缓存方案虽<strong>不会导致超卖</strong>，但因<strong>缓存不具备事务特性</strong>，极端情况下会存在缓存里的数据<strong>无法回滚</strong>，导致出现<strong>少卖</strong>的情况。且架构中的异步写库，也可能发生失败，导致多扣的数据丢失</p>
</blockquote>
<p>可以借助<strong>顺序写</strong>的特性，将扣减任务同步<strong>插入</strong>任务表，发现异常时，将任务表作为<strong>undolog</strong>进行回滚</p>
<p>可以解决由于<strong>网络不通</strong>、调用缓存<strong>扣减超时</strong>、在扣减到一半时缓存<strong>突然宕机</strong>（故障 failover）了。针对上述请求，都有相应的异常抛出，根据异常进行<strong>数据库回滚</strong>即可，最终任务库里的数据都是准的</p>
<p>更进一步：由于任务库是无状态的，可以进行水平分库，提升整体性能</p>
<h3 id="2、如何解决重复下单？"><a href="#2、如何解决重复下单？" class="headerlink" title="2、如何解决重复下单？"></a><strong>2、如何解决重复下单？</strong></h3><p>mysql唯一索引+分布式锁 </p>
<h3 id="3、如何防刷？"><a href="#3、如何防刷？" class="headerlink" title="3、如何防刷？"></a><strong>3、如何防刷？</strong></h3><p>IP限流 | 验证码 | 单用户 | 单设备 | IMEI | 源IP |均设置规则</p>
<h3 id="4、热key问题如何解决？"><a href="#4、热key问题如何解决？" class="headerlink" title="4、热key问题如何解决？"></a><strong>4、热key问题如何解决？</strong></h3><p>redis集群+本地缓存+限流+key加随机值分布在多个实例中 </p>
<p>1、<strong>缓存集群</strong>可以单节点进行<strong>主从复制和垂直扩容</strong></p>
<p>2、利用应用内的<strong>前置缓存</strong>，但是需注意需要设置上限</p>
<p>3、延迟不敏感，<strong>定时刷新</strong>，实时感知用主动刷新</p>
<p>4、和缓存穿透一样，限制逃逸流量，单请求进行数据<strong>回源并刷新前置</strong></p>
<p>5、无论如何设计，最后都要写一个<strong>兜底逻辑</strong>，千万级流量说来就来</p>
<h3 id="5、应对高并发的读请求"><a href="#5、应对高并发的读请求" class="headerlink" title="5、应对高并发的读请求"></a><strong>5、应对高并发的读请求</strong></h3><p>使用缓存策略将请求挡在上层中的缓存中</p>
<p>使用CDN，能静态化的数据尽量做到静态化，</p>
<p>加入限流（比如对短时间之内来自某一个用户，某一个IP、某个设备的重复请求做丢弃处理）</p>
<p><strong>资源隔离限流</strong>会将对应的资源按照指定的类型进行隔离，比如<strong>线程池</strong>和<strong>信号量</strong>。</p>
<ul>
<li><p>计数器限流，例如5秒内技术1000请求，超数后限流，未超数重新计数</p>
</li>
<li><p>滑动窗口限流，解决计数器不够精确的问题，把一个窗口拆分多滚动窗口</p>
</li>
<li><p>令牌桶限流，类似景区售票，售票的速度是固定的，拿到令牌才能去处理请求</p>
</li>
<li><p>漏桶限流，生产者消费者模型，实现了恒定速度处理请求，能够绝对防止突发流量</p>
<p>流量控制效果从好到差依次是：<strong>漏桶限流 &gt; 令牌桶限流 &gt; 滑动窗口限流 &gt; 计数器限流</strong></p>
<img src="https://tva1.sinaimg.cn/large/008i3skNly1gq6ja736ekj316o06640u.jpg" alt="image-20210504174148831" style="zoom:50%;" />

<p>其中，只有漏桶算法<strong>真正实现了恒定速度处理请求</strong>，能够绝对<strong>防止突发流量超过下游系统承载能力</strong>。<br>不过，漏桶限流也有个不足，就是需要分<strong>配内存资源缓存请求</strong>，这会增加内存的使用率。而<strong>令牌桶限流</strong>算法中的“桶”可以用一个整数表示，<strong>资源占用相对较小</strong>，这也让它成为最常用的限流算法。正是因为这些特点，<strong>漏桶限流和令牌桶限流</strong>经常在一些大流量系统中结合使用。</p>
</li>
</ul>
<h3 id="6、应对高并发的写请求"><a href="#6、应对高并发的写请求" class="headerlink" title="6、应对高并发的写请求"></a><strong>6、应对高并发的写请求</strong></h3><ul>
<li><p><strong>削峰</strong>：恶意用户拦截</p>
<p>对于单用户多次点击、单设备、IMEI、源IP均设置规则</p>
</li>
<li><p>采用比较成熟的<strong>漏桶算法、令牌桶</strong>算法，也可以使用<strong>guava</strong>开箱即用的限流算法</p>
<p>可以集群限流，但单机限流更加简洁和稳定</p>
</li>
<li><p>当前层<strong>直接过滤</strong>一定比例的请求，最大承载值前需要加上<strong>兜底逻辑</strong></p>
</li>
<li><p>对于已经无货的产品，<strong>本地缓存</strong>直接返回</p>
</li>
<li><p><strong>单独部署，减少对系统正常服务的影响，方便扩缩容</strong></p>
</li>
</ul>
<p>对于<strong>一段时间内的秒杀活动，需要保证写成功</strong>，我们可以使用 <strong>消息队列</strong>。</p>
<ul>
<li>削去秒杀场景下的峰值写流量——<strong>流量削峰</strong></li>
<li>通过异步处理简化秒杀请求中的业务流程——<strong>异步处理</strong></li>
<li>解耦，实现秒杀系统模块之间松耦合——<strong>解耦</strong></li>
</ul>
<p><strong>削去秒杀场景下的峰值写流量</strong></p>
<ul>
<li><strong>将秒杀请求暂存于消息队列</strong>，业务服务器响应用户“秒杀结果正在处理中。。。”，释放系统资源去处理其它用户的请求。</li>
<li><strong>削峰填谷</strong>，削平短暂的流量高峰，消息堆积会造成请求延迟处理，但秒杀用户对于短暂延迟有一定容忍度。秒杀商品有 1000 件，处理一次购买请求的时间是 500ms，那么总共就需要 500s 的时间。这时你部署 10 个队列处理程序，那么秒杀请求的处理时间就是 50s，也就是说用户需要等待 50s 才可以看到秒杀的结果，这是可以接受的。这时会<strong>并发 10 个</strong>请求到达数据库，并不会对数据库造成很大的压力。</li>
</ul>
<p><strong>通过异步处理简化秒杀请求中的业务流程</strong></p>
<p>​	先处理主要的业务，异步处理次要的业务。</p>
<ul>
<li>如主要流程是<strong>生成订单</strong>、<strong>扣减库存</strong>；</li>
<li>次要流程比如购买成功之后会给用户<strong>发优惠券</strong>，<strong>增加用户的积****分</strong>。</li>
<li>此时秒杀只要处理生成订单，扣减库存的耗时，发放优惠券、增加用户积分异步去处理了。</li>
</ul>
<p><strong>解耦</strong></p>
<p>​	实现秒杀系统模块之间松耦合将秒杀数据同步给数据团队，有两种思路：</p>
<ul>
<li>使用 HTTP 或者 RPC 同步调用，即提供一个接口，实时将数据推送给数据服务。<strong>系统的耦合度高</strong>，如果其中一个服务有问题，可能会导致另一个服务不可用。</li>
<li>使用消息队列<strong>将数据全部发送给消息队列</strong>，然后<strong>数据服务订阅这个消息队列</strong>，接收数据进行处理。</li>
</ul>
<h3 id="7、如何保证数据一致性"><a href="#7、如何保证数据一致性" class="headerlink" title="7、如何保证数据一致性"></a><strong>7、如何保证数据一致性</strong></h3><p><strong>CacheAside旁路缓存</strong>读请求不命中查询数据库，查询完成写入缓存，写请求更新数据库后删除缓存数据。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 延迟双删，用以保证最终一致性,防止小概率旧数据读请求在第一次删除后更新数据库</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">write</span><span class="params">(String key,Object data)</span>&#123;</span><br><span class="line">	redis.delKey(key);</span><br><span class="line">	db.updateData(data);</span><br><span class="line">	Thread.sleep(<span class="number">1000</span>);</span><br><span class="line">	redis.delKey(key);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>为防缓存失效这一信息丢失，可用消息队列确保。</p>
<ul>
<li>更新数据库数据；</li>
<li>数据库会将操作信息写入binlog日志当中；</li>
<li>另起一段非业务代码，程序订阅提取出所需要的数据以及key；</li>
<li>尝试删除缓存操作，若删除失败，将这些信息发送至消息队列；</li>
<li>重新从消息队列中获得该数据，重试操作；</li>
</ul>
<p>订阅<strong>binlog程序在mysql中有现成的中间</strong>件叫canal，重试机制，主要采用的是消息队列的方式。</p>
<p><strong>终极方案：请求串行化</strong></p>
<p>真正靠谱非秒杀的方案：将访问操作串行化</p>
<ol>
<li>先删缓存，将更新数据库的<strong>写操作放进有序队列中</strong></li>
<li>从缓存查不到的<strong>读操作也进入有序队列</strong></li>
</ol>
<p>需要解决的问题：</p>
<ol>
<li>读请求积压，大量超时，导致数据库的压力：限流、熔断</li>
<li>如何避免大量请求积压：将队列水平拆分，提高并行度。</li>
</ol>
<h3 id="8、可靠性如何保障"><a href="#8、可靠性如何保障" class="headerlink" title="8、可靠性如何保障**"></a>8、可靠性如何保障**</h3><p>​	由一个或多个sentinel实例组成sentinel集群可以监视一个或多个主服务器和多个从服务器。<strong>哨兵模式适合读请求远多于写请求的业务场景，比如在秒杀系统</strong>中用来缓存活动信息。 如果写请求较多，当集群 Slave 节点数量多了后，Master 节点同步数据的压力会非常大。</p>
<img src="https://tva1.sinaimg.cn/large/0081Kckwly1gluq6vlvglj30nw0e076f.jpg" alt="image-20201220231241725" style="zoom:50%;" />

<p>​	当主服务器进入下线状态时，sentinel可以将该主服务器下的某一从服务器升级为主服务器继续提供服务，从而保证redis的高可用性。 </p>
<h3 id="9、秒杀系统瓶颈-日志"><a href="#9、秒杀系统瓶颈-日志" class="headerlink" title="9、秒杀系统瓶颈-日志"></a>9、秒杀系统瓶颈-日志</h3><blockquote>
<p>秒杀服务单节点需要处理的请求 QPS 可能达到 10 万以上。一个请求从进入秒杀服务到处理失败或者成功，至少会产生两条日志。也就是说，高峰期间，一个秒杀节点每秒产生的日志可能达到 <strong>30 万条</strong>以上</p>
</blockquote>
<p>​	一块性能比较好的固态硬盘，每秒写的IOPS 大概在 3 万左右。也就是说，一个秒杀节点的每秒日志条数是固态硬盘 IOPS 的 10 倍，磁盘都扛不住，更别说通过网络写入到监控系统中。</p>
<ul>
<li><strong>每秒日志量远高于磁盘 IOPS</strong>，直接写磁盘会影响服务性能和稳定性</li>
<li>大量日志导致服务频繁分配，<strong>频繁释放内存，影响服务性能</strong>。</li>
<li>服务异常退出<strong>丢失大量日志</strong>的问题</li>
</ul>
<p><strong>解决方案</strong></p>
<ul>
<li><strong>Tmpfs</strong>，即临时文件系统，它是一种基于内存的文件系统。我们可以将秒杀服务写日志的文件放在临时文件系统中。相比直接写磁盘，在临时文件系统中写日志的性能至少<strong>能提升 100 倍</strong>，每当日志文件达到 20MB 的时候，就将<strong>日志文件转移到磁盘上</strong>，并将临时文件系统中的日志文件清空。</li>
<li>可以参考内存池设计，将给logger分配缓冲区，每一次的新写可以复用Logger对象</li>
<li>参考kafka的缓冲池设计，当缓冲区达到大小和间隔时长临界值时，调用Flush函数，减少丢失的风险</li>
</ul>
<p><strong>10、池化技术</strong></p>
<p><img src="https://tva1.sinaimg.cn/large/008i3skNly1gq6japwof2j31520na4mh.jpg" alt="image-20210504174220668"></p>
<p>​	通常可以采用<strong>循环队列</strong>来保存空闲连接。使用的时候，可以从队列头部取出连接，用完后将空闲连接放到队列尾部。Netty中利用带缓冲区的 channel 来充当队列。</p>
<h2 id="三、即时通信"><a href="#三、即时通信" class="headerlink" title="三、即时通信"></a>三、即时通信</h2><h3 id="1、单聊消息可靠传输"><a href="#1、单聊消息可靠传输" class="headerlink" title="1、单聊消息可靠传输"></a>1、<strong>单聊消息可靠传输</strong></h3><p>TCP保证消息可靠传输三板斧：超时、重传、确认。服务端和客户端通信MSG和ACK的共计6个报文</p>
<ul>
<li>请求报文（request，后简称为为R），客户端主动发送给服务端。</li>
<li>应答报文（acknowledge，后简称为A），服务器被动应答客户端的报文。</li>
<li>通知报文（notify，后简称为N），服务器主动发送给客户端的报文</li>
</ul>
<p><strong>在线消息流程：</strong></p>
<p>​		A 消息请求  <strong>MSG:R</strong>  &#x3D;&gt; S 消息应答  <strong>MSG:A</strong>  &#x3D;&gt; S 消息通知B  <strong>MSG:N</strong> </p>
<p>​		S 确认通知  <strong>ACK:N</strong>  &lt;&#x3D;  S 确认应答  <strong>ACK:A</strong>  &lt;&#x3D;  B确认请求S  <strong>ACK:R</strong> </p>
<p><strong>超时与重传、确认和去重：</strong></p>
<p>​	A发出了 <strong>MSG:R</strong> ，收到了<strong>MSG:A</strong>之后，在一个期待的时间内，如果没有收到<strong>ACK:N</strong>，A会尝试将 <strong>MSG:R</strong>  重发。可能A同时发出了很多消息，所以A需要在本地维护一个等待ack队列，并配合timer超时机制，来记录哪些消息没有收到<strong>ACK:N</strong>，定时重发。确认ACK<strong>保证必达</strong>，去重保证<strong>唯一</strong></p>
<p><strong>离线消息流程</strong></p>
<p>​	原方案：根据离线好友的标识，交互拉取指定的消息</p>
<p><img src="https://tva1.sinaimg.cn/large/0081Kckwly1gm8kxci29zj30b305974z.jpg" alt="IM消息送达保证机制实现(二)：保证离线消息的可靠投递_2.png"></p>
<p>优化的方案：</p>
<ul>
<li>如用户<strong>勾选全量</strong>则返回计数，在用户点击时拉取。</li>
<li>如用户未勾选全量则返回<strong>最近全部离线消息</strong>，客户端针对<strong>用户id进行计算</strong>。</li>
<li>全量离线信息可以通过客户端异步线程分页拉取，减少卡顿</li>
<li>将ACK和分页第二次拉取的报文重合，可以较少离线消息拉取交互的次数</li>
</ul>
<h3 id="2、群聊消息如何保证不丢不重"><a href="#2、群聊消息如何保证不丢不重" class="headerlink" title="2、群聊消息如何保证不丢不重"></a><strong>2、群聊消息如何保证不丢不重</strong></h3><blockquote>
<p>在线的群友能第一时间收到消息；<br>离线的群友能在登陆后收到消息。</p>
</blockquote>
<p><img src="https://tva1.sinaimg.cn/large/0081Kckwly1gm8jswr3poj30hh078dg2.jpg" alt="IM群聊消息如此复杂，如何保证不丢不重？_1.jpg"></p>
<ul>
<li>群消息发送者x向server发出群消息；</li>
<li>server去db中查询群中有多少用户(x,A,B,C,D)；</li>
<li>server去cache中查询这些用户的在线状态；</li>
<li>对于群中在线的用户A与B，群消息server进行实时推送；</li>
<li>对于群中离线的用户C与D，群消息server进行离线存储。</li>
</ul>
<p>​    对于同一份群消息的内容，多个离线用户存储了很多份。假设群中有200个用户离线，离线消息则冗余了200份，这极大的增加了数据库的存储压力</p>
<ul>
<li><p>离线消息表只存储用户的群离线消息msg_id，降低数据库的冗余存储量</p>
</li>
<li><p>加入应用层的ACK，才能保证群消息一定到达，服务端幂等性校验及客户端去重，保证不重复</p>
</li>
<li><p>每条群消息都ACK，会给服务器造成巨大的冲击，通过批量ACK减少消息风暴扩散系数的影响</p>
</li>
<li><p>群离线消息过多：拉取过慢，可以通过分页懒拉取改善。</p>
</li>
</ul>
<h3 id="3、如何保证消息的时序性"><a href="#3、如何保证消息的时序性" class="headerlink" title="3、如何保证消息的时序性"></a>3、<strong>如何保证消息的时序性</strong></h3><p>方案：</p>
<ul>
<li>Id通过借鉴微信号段+跳跃的方式保证趋势递增</li>
<li>单聊借鉴数据库设计，单点序列化同步到其他节点保证多机时序</li>
<li>群聊消息使用单点序列化保证各个发送者的消息相对时序</li>
</ul>
<p><img src="https://tva1.sinaimg.cn/large/0081Kckwly1gm8m1ge2ksj30j707gt96.jpg" alt="如何保证IM实时消息的“时序性”与“一致性”？_10.jpg"></p>
<p>优化：</p>
<ul>
<li>利用服务器单点序列化时序，可能出现服务端收到消息的时序，与发出序列不一致</li>
<li>在A往B发出的消息中，加上发送方A本地的一个绝对时序，来表示接收方B的展现时序。</li>
<li>群聊消息保证一个群聊落在一个service上然后通过本地递增解决全局递增的瓶颈问题</li>
</ul>
<h3 id="4：推拉结合"><a href="#4：推拉结合" class="headerlink" title="4：推拉结合"></a><strong>4：推拉结合</strong></h3><p>历史方案：</p>
<ul>
<li>服务器在缓存集群里存储所有用户的在线状态 -&gt; 保证状态可查</li>
<li>用户状态实时变更，任何用户登录&#x2F;登出时，需要推送所有好友更新状态</li>
<li>A登录时，先去数据库拉取自己的好友列表，再去缓存获取所有好友的在线状态</li>
</ul>
<p><strong>“消息风暴扩散系数”</strong>是指一个消息发出时，变成N个消息的扩散系数，这个系数与业务及数据相关，一定程度上它的大小决定了技术采用推送还是拉取。</p>
<p>优化方案：</p>
<ul>
<li><strong>好友状态推拉结合</strong>，首页置顶亲密、当前群聊，采用推送，否则可以采用轮询拉取的方式同步；</li>
<li><strong>群友的状态</strong>，由于消息风暴扩散系数过大，可以采用按需拉取，延时拉取的方式同步；</li>
<li><strong>系统消息&#x2F;开屏广告等</strong>这种实时产生的消息，可以采用推送的方式获取消息；</li>
</ul>
<h3 id="5、好友推荐"><a href="#5、好友推荐" class="headerlink" title="5、好友推荐"></a>5、好友推荐</h3><p>Neo4j 图谱数据库</p>
<h2 id="四、智慧社区"><a href="#四、智慧社区" class="headerlink" title="四、智慧社区"></a>四、智慧社区</h2><p>​	18年初，针对我们Dubbo框架的智慧楼宇项目的单体服务显得十分笨重，需要采用微服务的形式进行架构的重新设计，当时，我阅读了<em>Eric Evans</em> 写的《领域驱动设计：软件核心复杂性应对之道》和<em>Martin</em> <em>fowler</em>的《微服务架构：<em>Microservice</em>》两本重量级书籍，书中了解到转型微服务的重要原因之一就是利用<strong>分治的思想</strong>减少系统的复杂性，是一种针对<strong>复杂问题的宏观设计</strong>，来应对系统后来规模越来越大，维护越来越困难的问题。然而，拆分成微服务以后，并<strong>不意味着每个微服务都是各自独立地运行</strong>，而是彼此协作地组织在一起。这就好像一个团队，<strong>规模越大越需要一些方法来组织</strong>，这正是我们需要DDD模型为我们的架构设计提供理论并实践的方法。</p>
<p>​	当时每次版本更新迭代动辄十几个微服务同时修改，有时一个简单的数据库字段变更，也需要同时变更多个微服务，引起了团队的反思：微服务化看上去并没有减少我们的工作量。《企业架构设计》中对于微服务的定义是<strong>小而专</strong>，但在起初的设计时，我们只片面的<strong>理解了小却忽视了专</strong>，此时我们才意识到拆分的关键是要保证微服务内高内聚，微服务间低耦合。</p>
<h3 id="物联网架构"><a href="#物联网架构" class="headerlink" title="物联网架构"></a><strong>物联网架构</strong></h3><blockquote>
<p>物联网是互联网的<strong>外延</strong>。将用户端<strong>延伸</strong>和扩展到物与人的连接。物联网模式中，所有<strong>物品与网络连接</strong>，并进行通信和场景联动。互联网通过<strong>电脑、移动终端</strong>等设备将参与者联系起来，形成的一种全新的<strong>信息互换方式</strong></p>
</blockquote>
<h4 id="DCM系统架构"><a href="#DCM系统架构" class="headerlink" title="DCM系统架构"></a>DCM系统架构</h4><ul>
<li><strong>设备感知层</strong>（Device）：利用射频识别、二维码、传感器等技术进行数据采集</li>
<li><strong>网络传输层</strong>（Connect）：依托通信网络和协议，实现可信的信息交互和共享</li>
<li><strong>应用控制层</strong>（Manage）：分析和处理海量数据和信息，实现智能化的决策和控制</li>
</ul>
<img src="https://tva1.sinaimg.cn/large/008i3skNly1gq6jc1stt3j31380lswso.jpg" alt="image-20210504174337327" style="zoom:50%;" />

<h4 id="三要素"><a href="#三要素" class="headerlink" title="三要素"></a><strong>三要素</strong></h4><ul>
<li><strong>设备联网</strong>：通过不同的网络协议和通信标准，实现设备与控制端的连接</li>
<li><strong>云端分析</strong>：提供监控、存储、分析等数据服务，以及保障客户的业务数据安全</li>
<li><strong>云边协同</strong>：云端接受设备上报数据，下发设备管控指令</li>
</ul>
<h4 id="云-x2F-边-x2F-端协同"><a href="#云-x2F-边-x2F-端协同" class="headerlink" title="云 &#x2F; 边 &#x2F; 端协同"></a>云 &#x2F; 边 &#x2F; 端协同</h4><p><strong>云端计算</strong>、<strong>终端计算</strong>和<strong>边缘计算</strong>是一个协同的系统，根据用户场景、资源约束程度、业务实时性等进行动态调 配，形成可靠、低成本的应用方案。从过去几年的发展积累来看，AI 已在物联网多个层面进行融合，比我们合作的海康威视、旷视宇视、商汤科技等纷纷发布了物联网AI相关平台和产品，和移动和小区进行了紧密的融合。</p>
<img src="https://tva1.sinaimg.cn/large/008eGmZEly1gn9kwux9vjj312w0li138.jpg" alt="image-20210202225351673" style="zoom:50%;" />



<h4 id="物联网平台接入"><a href="#物联网平台接入" class="headerlink" title="物联网平台接入"></a>物联网平台接入</h4><img src="https://static-aliyun-doc.oss-accelerate.aliyuncs.com/assets/img/zh-CN/3199158061/p132750.png" alt="企业基于物联网平台的业务链路" style="zoom:50%;" />

<p>向下连接海量设备，支撑设备<strong>数据采集上云</strong>；</p>
<p>向上通过调用<strong>云端API</strong>将指令下发至设备端，实现<strong>远程控制</strong>。</p>
<p><strong>上行数据链路</strong></p>
<ul>
<li>设备建立<strong>MQTT</strong>长连接，上报数据（发布Topic和Payload）到物联网平台</li>
<li>物联网平台通过<strong>配置</strong>规则，通过<strong>RocketMQ</strong>、<strong>AMQP</strong>等队列转发到业务平台</li>
</ul>
<p><strong>下行指令链路</strong></p>
<ul>
<li>业务服务器基于<strong>HTTPS</strong>协议调用的API接口，发布Topic指令到物联网平台。</li>
<li>物联网平台通过<strong>MQTT</strong>协议，使用发布（指定Topic和Payload）到<strong>设备端</strong>。</li>
</ul>
<h4 id="门锁接入"><a href="#门锁接入" class="headerlink" title="门锁接入"></a>门锁接入</h4><p><strong>WIFI门锁</strong>：<strong>非保活</strong> 平常处于断电休眠状态，需要<strong>MCU</strong> <strong>唤醒</strong>才能传输和发送数据</p>
<p><strong>蓝牙门锁</strong>：<strong>MCU串口对接</strong>和<strong>SDK对接</strong>，近距离<strong>单点登录</strong>和远距离<strong>网关登录</strong></p>
<p><strong>Zigbee门锁</strong>：<strong>非保活</strong> 但是保持心跳，<strong>MCU</strong>对接，<strong>Zigbee协议</strong>控制。</p>
<p><strong>NB-Iot门锁</strong>：可以通过<strong>公网</strong>连接，把门禁变成<strong>SAAS</strong>服务，<strong>MCU</strong></p>
<table>
<thead>
<tr>
<th>名词</th>
<th>解释</th>
</tr>
</thead>
<tbody><tr>
<td><strong>SaaS</strong></td>
<td><strong>Software-as-a-Service</strong> ，提供给客户的服务是运营商运行在云计算基础设施上的应用程序。<strong>用户可以在各种设备上通过客户端界面访问应用</strong>，例如计算机浏览器。用户不需要管理或控制任何云计算基础设施，包括网络、服务器、操作系统、存储等资源，一切由 SaaS 提供商管理和运维。</td>
</tr>
<tr>
<td><strong>PaaS</strong></td>
<td><strong>Platform-as-a-Service</strong>，表示平台即服务理念，客户不需要管理或控制底层的云基础设施，包括网络、服务器、操作系统、存储等，但<strong>客户能控制部署的应用程序</strong>，也可能控制运行应用程序的托管环境配置。</td>
</tr>
<tr>
<td><strong>IaaS</strong></td>
<td>I<strong>nfrastructure-as-a-Service</strong> ，表示基础设施即服务理念，提供的服务是对所有计算基础设施的利用，包括 CPU、内存、存储、网络等其它计算资源。<strong>用户能够部署和运行任意软件，包括操作系统和应用程序。</strong></td>
</tr>
</tbody></table>
<h4 id="各种协议"><a href="#各种协议" class="headerlink" title="各种协议"></a>各种协议</h4><p><strong>HTTP协议（CS用户上网）</strong></p>
<p>HTTP协议是典型的CS通讯模式，由<strong>客户端主动</strong>发起连接，向服务器请求<strong>XML或JSON数据</strong>。该协议最早是为了适用web浏览器的<strong>上网浏览场景</strong>和设计的，目前在<strong>PC、手机、pad</strong>等终端上都应用广泛，但并<strong>不适用于物联网场景</strong></p>
<ul>
<li>由于必须由设备主动向服务器发送数据，难以主动向设备推送数据。</li>
<li>物联网场景中的<strong>设备多样</strong>，运算<strong>受限的设备</strong>，难以实现JSON数据格式的解析</li>
</ul>
<p><strong>RESTAPI（松耦合调用）</strong></p>
<p>REST&#x2F;HTTP主要为了<strong>简化</strong>互联网中的系统架构，<strong>快速实现</strong>客户端和服务器之间交互的<strong>松耦合</strong>，降低了客户端和服务器之间的<strong>交互延迟</strong>。因此适合在物联网的应用层面，通过REST<strong>开放</strong>物联网中资源，实现服务被其他应用所调用。</p>
<p><strong>CoAP协议（无线传感）</strong></p>
<blockquote>
<p>简化了HTTP协议的<strong>RESTful API</strong>，它适用于在<strong>资源受限</strong>的通信的IP网络。</p>
</blockquote>
<p><strong>MQTT协议（低带宽）</strong></p>
<blockquote>
<p>MQTT协议采用<strong>发布&#x2F;订阅</strong>模式，物联网终端都通过TCP连接到云端，云端通过主题的方式管理各个设备关注的通讯内容，<strong>负责</strong>将设备与设备之间<strong>消息的转发</strong></p>
</blockquote>
<p>适用范围：在低带宽、不可靠的集中<strong>星型网络架构</strong>（hub-and-spoke），不适用设备与设备之间通信，设备<strong>控制能力弱</strong>，另外<strong>实时性较差</strong>，一般都在<strong>秒级</strong>。协议要<strong>足够轻量</strong>，方便嵌入式设备去快速地解析和响应。具备<strong>足够的灵活性</strong>，使其足以为 IoT 设备和服务的多样化提供支持。应该设计为<strong>异步消息协议</strong>，这么做是因为大多数 IoT 设备的网络延迟很可能非常不稳定，若使用同步消息协议，IoT 设备需要等待服务器的响应，必须是<strong>双向通信</strong>，服务器和客户端应该可以互相发送消息。</p>
<p><strong>AMQP协议（互操作性）</strong></p>
<blockquote>
<p>用于业务系统例如PLM，ERP，MES等进行数据交换。</p>
</blockquote>
<p>　　适用范围：最早应用于金融系统之间的交易消息传递，在物联网应用中，主要适用于移动手持设备与后台数据中心的通信和分析。</p>
<p><strong>XMPP协议（即时通信）</strong></p>
<blockquote>
<p>开源形式组织产生的网络即时通信协议。被IETF国际标准组织完成了标准化工作</p>
</blockquote>
<p>　　适用范围：<strong>即时通信</strong>的应用程序，还能用在<strong>协同工具</strong>、游戏等。</p>
<p>​	XMPP在通讯的业务流程上是更适合物联网系统的，开发者不用花太多心思去解决设备通讯时的业务通讯流程，相对开发成本会更低。但是HTTP协议中的安全性以及计算资源消耗的硬伤并没有得到本质的解决。</p>
<p><strong>JMS （Java消息服务）</strong></p>
<p>​	Java消息服务（Java Message Service）应用程序接口，是一个Java平台中关于面向消息中间件（MOM）的API，用于在两个应用程序之间，或分布式系统中发送消息，进行异步通信。</p>
<p><strong>Zigbee协议</strong></p>
<p>​	低功耗，它保持IEEE 802.15.4（2003）标准</p>
<h3 id="IOT流量洪峰"><a href="#IOT流量洪峰" class="headerlink" title="IOT流量洪峰"></a>IOT流量洪峰</h3><p>智慧社区IOT领域，不管是嵌入式芯片还是应用服务器都需要传递消息，常见上行的消息有：<strong>人脸识别开门、烟感雾感告警</strong>、共享充电桩充电，下行的<strong>广告下发、NB门禁开门指令、</strong>超级门板显示等，由于物联网设备时不时会<strong>故障和断网导致大量的流量洪峰</strong>，传统消息队列需要针对性优化。</p>
<ul>
<li><p><strong>上下行拆分</strong></p>
<p>上行消息特征：并发量<strong>高</strong>、可靠性和<strong>时延性要求低</strong></p>
<p>下行消息特征：并发量<strong>低</strong>、控制指令的<strong>成功率要求高</strong></p>
</li>
<li><p><strong>海量Topic下性能</strong></p>
<p><strong>Kafka</strong>海量Topic性能会<strong>急剧下降</strong>，Zookeeper协调也有瓶颈</p>
<p><strong>多泳道消息队列</strong>可以实现IoT消息队列的故障<strong>隔离</strong></p>
</li>
<li><p><strong>实时消息优先处理</strong></p>
<p>NB门禁实时产生的开门指令必须<strong>第一优先级处理</strong>，堆积的消息降级</p>
<p>设计成<strong>无序、不持久化</strong>的，并与传统的FIFO队列隔离</p>
</li>
<li><p><strong>连接、计算、存储分离</strong></p>
<p>Broker只做<strong>流转分发</strong>，实现<strong>无状态</strong>和<strong>水平扩展</strong></p>
<p>计算交给<strong>Flink</strong>，存储交给nosqlDB，实现<strong>高吞吐写</strong></p>
</li>
<li><p><strong>消息策略-推拉结合</strong></p>
<p>MQTT针对电池类物联网设备，AMQP针对安全性较高的门禁设备</p>
<p>消费端离线时存到queue，在线时将<strong>实时消息和从queue中拉取的消息</strong>一起推送</p>
</li>
</ul>
<p><img src="https://tva1.sinaimg.cn/large/008eGmZEly1goboitd4h2j30u00ciq3i.jpg" alt="img"></p>
<p><strong>如果解决海量Topic</strong></p>
<p>​	首先要做的就是分区、分组等水平拆分的方式，接下来考虑单实例如何处理更多Topic，传统消息队列在海量Topic下顺序写会退化成随机写，性能大幅下降</p>
<ul>
<li><p><strong>人工Sharding</strong>：部署多个Kafka集群，通过不同mq连接来隔离</p>
</li>
<li><p><strong>合并Topic</strong>，客户端封装subTopic。比如一个服务的N个统计项，会消费到无关消息</p>
<p>​	基于这个思路，使用<strong>Kafka Streams</strong>或者<strong>Hbase列</strong>存储来聚合</p>
</li>
</ul>
<p>针对单个Topic海量订阅的问题，<strong>可以在上层封装广播组件来协调批量发送</strong></p>
<p><img src="https://tva1.sinaimg.cn/large/008eGmZEly1gobohzda8fj30u00cgaax.jpg" alt="img"></p>
<h3 id="社区直播带货"><a href="#社区直播带货" class="headerlink" title="社区直播带货"></a>社区直播带货</h3><blockquote>
<p>使用<strong>端 &#x2F; 边 &#x2F; 云</strong>三级架构，客户端加密传输，边缘节点转发、云侧转码并持久化</p>
</blockquote>
<h4 id="产品的背景"><a href="#产品的背景" class="headerlink" title="产品的背景"></a><strong>产品的背景</strong></h4><blockquote>
<p>上线时间，从调研到正式上线用了 3个月时间，上线后一个月内就要经历双十二挑战。在这么紧的上线时间要求下，需要用到公司提供的所有优势，包括<strong>cdn网络，直播牌照</strong>等</p>
</blockquote>
<h4 id="面临的挑战"><a href="#面临的挑战" class="headerlink" title="面临的挑战"></a>面临的挑战</h4><ul>
<li><p>直播数据是<strong>实时</strong>生成的，所有不能够进行<strong>预缓存</strong></p>
</li>
<li><p>直播随时会发生，举办热点活动，相关服务器资源需要<strong>动态分配</strong></p>
</li>
<li><p>直播的延迟对于用户体验影响很大，需要控制在<strong>秒级</strong></p>
</li>
<li><p>直播sdk是内嵌在社区应用里的，整体要求不能超过5M</p>
</li>
</ul>
<h4 id="协议的比较"><a href="#协议的比较" class="headerlink" title="协议的比较"></a>协议的比较</h4><table>
<thead>
<tr>
<th>协议</th>
<th>上线时间</th>
<th>网络兼容</th>
<th>端对端延迟</th>
<th>应用大小</th>
<th>问题</th>
</tr>
</thead>
<tbody><tr>
<td>WebRTC</td>
<td></td>
<td>✗</td>
<td></td>
<td></td>
<td>Webrtc 基于 UDP，和社区应用的网络架构不兼容</td>
</tr>
<tr>
<td>HTTP Upload</td>
<td></td>
<td></td>
<td>✗</td>
<td></td>
<td>会导致网络高延迟</td>
</tr>
<tr>
<td>Custom Protocol</td>
<td>✗</td>
<td></td>
<td></td>
<td></td>
<td>工程师需要实现自己的客户端与服务端的库，无法按时上线</td>
</tr>
<tr>
<td>Proprietary</td>
<td></td>
<td></td>
<td></td>
<td>✗</td>
<td>协议就需要几兆的空间，超出额度</td>
</tr>
<tr>
<td>RTMPS</td>
<td>✔</td>
<td>✔</td>
<td>✔</td>
<td>✔</td>
<td>TCP实时传输消息协议，更安全更可靠</td>
</tr>
</tbody></table>
<h4 id="整体流程"><a href="#整体流程" class="headerlink" title="整体流程"></a>整体流程</h4><p><strong>RTMPS</strong>：基于TCP实时传输消息协议，更安全更可靠</p>
<p><strong>MPEG-DASH</strong>：是一种基于HTTP协议自适应比特率流媒体技术，应对复杂的环境</p>
<p><img src="https://i.loli.net/2021/01/25/zjwC7B8fdcpDytA.png" alt="image-20210125145103417"></p>
<ol>
<li><p>直播端使用 <strong>RTMPS</strong> 协议发送直播数据到<strong>边缘节点</strong>（POP）</p>
</li>
<li><p>POP 使用<strong>RTMP</strong>发送数据到数据中心（DC）</p>
</li>
<li><p>DC 将数据编码成<strong>不同的清晰度</strong>并进行持久化存储</p>
<p><strong>云端转码</strong>主要有<strong>两种分辨率</strong>400x400 和 720x720. </p>
</li>
<li><p>播放端通过 <strong>MPEG-DASH</strong> &#x2F; RTMPS 协议接收直播数据</p>
<p>如果用户网络不好**<a target="_blank" rel="noopener" href="https://www.cloudflare.com/zh-cn/learning/video/what-is-mpeg-dash/">MPEG-DASH</a>**会自动转换成低分辨率</p>
</li>
</ol>
<h4 id="直播流程"><a href="#直播流程" class="headerlink" title="直播流程"></a><strong>直播流程</strong></h4><img src="https://i.loli.net/2021/01/25/GITnbhDqPdtZY2k.png" alt="image-20210125153606264" style="zoom:50%;" />

<ol>
<li><p>直播端使用 <strong>RTMPS</strong> 协议发送直播流数据到 POP 内的就近的代理服务器</p>
</li>
<li><p>代理服务器<strong>转发</strong>直播流数据到数据中心的网关服务器（<strong>443转80</strong>）</p>
</li>
<li><p>网关服务器使用<strong>直播 id 的一致性哈希算法</strong>发送直播数据到指定的编码服务器</p>
</li>
<li><p>编码服务器有几项职责：</p>
<ul>
<li><p>4.1 <strong>验证直播数据</strong>的格式是否正确。</p>
</li>
<li><p>4.2 <strong>关联</strong>直播 id 以及编码服务器第一映射，保证客户端即使连接中断或者服务器扩容时，在<strong>重新连接</strong>的时候依然能够连接到相同的编码服务器</p>
</li>
<li><p>4.3 使用直播数据<strong>编码成不同解析度</strong>的输出数据</p>
</li>
<li><p>4.4 使用 <strong>DASH</strong> 协议输出数据并<strong>持久化</strong>存储</p>
</li>
</ul>
</li>
</ol>
<h4 id="播放流程"><a href="#播放流程" class="headerlink" title="播放流程"></a>播放流程</h4><img src="https://i.loli.net/2021/01/25/Lo5N8QYlI2DPjyO.png" alt="image-20210125154758184" style="zoom:50%;" />

<ol>
<li>播放端使用 HTTP <strong>DASH</strong> 协议向 POP 拉取直播数据</li>
<li>POP 里面的代理服务器会检查数据是否已经在 POP 的<strong>缓存</strong>内。如果是的话，缓存会返回数据给播放端，否则，代理服务器会向 DC 拉取直播数据</li>
<li>DC 内的代理服务器会检查数据是否在 DC 的缓存内，如果是的话，缓存会返回数据给 POP，并更新 POP 的缓存，再返回给播放端。不是的话，代理服务器会使用一致性哈希算法向对应的编码服务器请求数据，并更新 DC 的缓存，返回到 POP，再返回到播放端。</li>
</ol>
<p><strong>收获</strong></p>
<ol>
<li>项目的成功不，代码只是内功，考虑适配不同的网络、利用可利用的资源</li>
<li>惊群效应在热点服务器以及许多组件中都可能发生</li>
<li>开发大型项目需要对<strong>吞吐量和时延</strong>、<strong>安全和性能</strong>做出妥协</li>
<li>保证架构的灵活度和可扩展性，为内存、服务器、带宽耗尽做好规划</li>
</ol>
<h3 id="直播高可用方案"><a href="#直播高可用方案" class="headerlink" title="直播高可用方案"></a><strong>直播高可用方案</strong></h3><p><strong>网络可靠性</strong>：</p>
<ul>
<li>根据<strong>网络连接速度</strong>来自动调整视频质量</li>
<li>使用<strong>短时间的数据缓存</strong>来解决直播端不稳定，瞬间断线的问题</li>
<li>根据<strong>网络质量自动降级</strong>为音频直播以及播放</li>
</ul>
<p><strong>惊群效应：</strong></p>
<ul>
<li>当多个播放端向同一个 POP 请求直播数据的时候，如果数据不在缓存中</li>
<li>这时候只有一个请求 A 会到 DC 中请求数据，其他请求会等待结果</li>
<li>但是如果请求 A 超时没有返回数据的话，所有请求会一起向 DC 访问数据</li>
<li>这时候就会加大 DC 的压力，触发惊群效应</li>
<li>解决这个问题的方法就是通过<strong>实际的情况</strong>来调整请求超时的时间。这个时间如果太长的话会带来直播的延迟，太短的话会经常触发惊群效应（<strong>每个时间窗口只允许触发一次</strong>，设置允许最大回源数量）</li>
</ul>
<h3 id="性能优化方案"><a href="#性能优化方案" class="headerlink" title="性能优化方案"></a><strong>性能优化方案</strong></h3><p><img src="https://tva1.sinaimg.cn/large/008eGmZEly1gobogaxxjkj304v0e7t93.jpg" alt="img"></p>
<p><strong>数据库优化：</strong> 数据库是最容易成为瓶颈的组件，考虑从 SQL 优化或者数据库本身去提高它的性能。如果瓶颈依然存在，则会考虑分库分表将数据打散，如果这样也没能解决问题，则可能会选择缓存组件进行优化</p>
<p><strong>集群最优：</strong>存储节点的问题解决后，计算节点也有可能发生问题。一个集群系统如果获得了水平扩容的能力，就会给下层的优化提供非常大的时间空间，由最初的 3 个节点，扩容到最后的 200 多个节点，但由于人力问题，服务又没有什么新的需求，下层的优化就一直被搁置着。</p>
<p><strong>硬件升级：</strong>水平扩容不总是有效的，原因在于单节点的计算量比较集中，或者 JVM 对内存的使用超出了宿主机的承载范围。在动手进行代码优化之前，我们会对节点的硬件配置进行升级。</p>
<p><strong>代码优化</strong>：代码优化是提高性能最有效的方式，但需要收集一些数据，这个过程可能是服务治理，也有可能是代码流程优化。比如JavaAgent 技术，会无侵入的收集一些 profile 信息，供我们进行决策。</p>
<p><strong>并行优化：</strong>并行优化是针对速度慢的接口进行并行调用。所以我们通常使用 ContDownLatch 对需要获取的数据进行并行处理，效果非常不错，比如在 200ms 内返回对 50 个耗时 100ms 的下层接口的调用。</p>
<p><strong>JVM 优化</strong>： JVM 发生问题时，优化会获得巨大的性能提升。但在 JVM 不发生问题时，它的优化效果有限。但在代码优化、并行优化、JVM 优化的过程中，JVM 的知识却起到了关键性的作用</p>
<p><strong>操作系统优化：</strong>操作系统优化是解决问题的杀手锏，比如像 HugePage、SWAP、“CPU 亲和性”这种比较底层的优化。但就计算节点来说，对操作系统进行优化并不是很常见。运维在背后会做一些诸如文件句柄的调整、网络参数的修改，这对于我们来说就已经够用了</p>
<h3 id="流量回放自动化测试"><a href="#流量回放自动化测试" class="headerlink" title="流量回放自动化测试"></a>流量回放自动化测试</h3><blockquote>
<p>系统级的重构，测试回归的工作量至少都是以月为单位，对于人力的消耗巨大。一种应对方案是，先不改造，到系统实在扛不住了再想办法。另一种应对方案是，先暂停需求，全力进行改造。但在实际工作场景中，上述应对策略往往很难实现。</p>
</blockquote>
<p>场景：</p>
<p>1、读服务均是查询，它是无状态的。</p>
<p>2、不管是架构升级还是日常需求，读服务对外接口的出入参格式是没有变化的</p>
<img src="https://tva1.sinaimg.cn/large/008i3skNly1gq6jd95rpij315g0hqn5q.jpg" alt="image-20210504174447049" style="zoom:50%;" />

<ul>
<li><p><strong>日志收集</strong>，主要作用是收集被测系统的真实用户请求，基于一定规则处理后作为系统用例；</p>
<p>Spring 里的 Interceptor 、Servlet 里的 Filter 过滤器，对所有请求的入参和出参进行记录，并通过 MQ 发送出去。（注意错峰、过滤写、去重等）</p>
</li>
<li><p>数据回放是基于收集的用例，对被测系统进行数据回放，发起自动化测试回归；</p>
<p><strong>离线回放：</strong>只调用新服务，将返回的数据和日志里的出参进行比较，<strong>日志比较大</strong></p>
<p><strong>实时回放：</strong>去实时调用线上系统和被测系统，并存储实时返回回放的结果信息，<strong>线上有负担</strong></p>
<p><strong>并行回放：</strong>新版本不即时上线，每次调用老版本接口时概率实时回放新版本接口，<strong>耗时间周期</strong></p>
</li>
<li><p><strong>差异对比</strong>，通过差异对比自动发现与预期不一致的用例，进而确定 Bug。</p>
<p>采用文本对比，可以直观地看到哪个字段数据有差异，从而更快定位到问题。正常情况下，只要存在差异的数据，均可认为是 Bug，是需要进行修复的。</p>
</li>
</ul>
<p><strong>方法论</strong></p>
<p><strong>Discovery</strong></p>
<p>​				考虑企业战略，分析客户需求，制定产品目标</p>
<p>​					由外到内：竞争对手的方案，为什么做，以后怎么发展，如何去优化。</p>
<p>​					自上而下：基于公司的战略，考虑自身能力和所处环境。</p>
<p>​					自下而上：从资源、历史问题、优先级出发，形成一套可行性实施方法。</p>
<p><strong>Define</strong></p>
<p>​				基于收集的信息，综合跨业务线的抽象能力和服务，先做什么后做什么，怎么做</p>
<p>​					设计新的架构，重点设计解决痛点问题。</p>
<p>​					拆分业务领域，重点划分工作临界上下文。</p>
<p><strong>Design</strong></p>
<p>​				详细的业务设计，功能设计，交付计划，考核计划</p>
<p>​					产品愿景，产品形态，相关竞品方案对比，价值、优势、收益</p>
<p>​					梳理业务范围，要知道电商领域四大流（信息流、商流、资金流、物流）</p>
<p>​					MVP最小可用比，让客户和老大看到结果，最后通编写story把故事编圆</p>
<p><strong>Delivery</strong></p>
<p>​				交付阶段，根据反馈及时调整中台战略，减少损失和增大收益</p>
<p>​					合理制定每个阶段的绩效考核目标：</p>
<p>​				40%稳定+25%业务创新+20%服务接入+15%用户满意度</p>
<h1 id="七、架构设计"><a href="#七、架构设计" class="headerlink" title="七、架构设计"></a><strong>七、架构设计</strong></h1><h2 id="1、社区系统的架构"><a href="#1、社区系统的架构" class="headerlink" title="1、社区系统的架构"></a>1、社区系统的架构</h2><img src="https://tva1.sinaimg.cn/large/008eGmZEly1gmqv8zyhkqj311s0u0q7s.jpg" alt="image-20210117182546782" style="zoom:40%;" />

<p><strong>系统拆分</strong></p>
<p>​		通过DDD领域模型，对服务进行拆分，将一个系统拆分为多个子系统，做成SpringCloud的微服务。微服务设计时要尽可能做到少扇出，多扇入，根据服务器的承载，进行客户端负载均衡，通过对核心服务的上游服务进行限流和降级改造。</p>
<p>​	一个服务的代码不要太多，1 万行左右，两三万撑死了吧。</p>
<p>​	大部分的系统，是要进行<strong>多轮拆分</strong>的，第一次拆分，可能就是将以前的多个模块该拆分开来了，比如说将电商系统拆分成<strong>订单系统、商品系统、采购系统、仓储系统、用户系统</strong>等等吧。</p>
<p>​	但是后面可能每个系统又变得越来越复杂了，比如说采购系统里面又分成了<strong>供应商管理系统、采购单管理系统</strong>，订单系统又拆分成了<strong>购物车系统、价格系统、订单管理</strong>系统。</p>
<p><strong>CDN、Nginx静态缓存、JVM缓存</strong></p>
<p>​	利用Java的模板thymeleaf可以将页面和数据动态渲染好，然后通过Nginx直接返回。动态数据可以从redis中获取。其中redis里的数据由一个缓存服务来进行消费指定的变更服务。</p>
<p>​	商品数据，每条数据是 10kb。100 条数据是 1mb，10 万条数据是 1g。常驻内存的是 200 万条商品数据，占用内存是 20g，仅仅不到总内存的 50%。目前高峰期每秒就是 3500 左右的请求量。</p>
<p><strong>缓存</strong></p>
<p>Redis cluster，10 台机器，5主5从，5 个节点对外提供读写服务，<strong>每个节点的读写高峰 QPS</strong> 可能可以达到每秒 5 万，<strong>5 台机器最多是 25 万读写</strong>请求每秒。</p>
<p>​	<strong>32G 内存+ 8 核 CPU + 1T</strong> 磁盘，但是分配给 <strong>Redis 进程的是 10g 内存</strong>，一般线上生产环境，Redis 的内存尽量不要超过 10g，超过 10g 可能会有问题。</p>
<p>​	因为每个主实例都挂了一个从实例，所以是<strong>高可用</strong>的，任何一个主实例宕机，都会自动故障迁移，Redis 从实例<strong>会自动变成主实例</strong>继续提供读写服务。</p>
<p><strong>MQ</strong></p>
<p>​	可以通过消息队列对微服务系统进行<a href="#1%E3%80%81%E6%8B%86%E5%88%86%E5%BE%AE%E6%9C%8D%E5%8A%A1">解耦</a>，异步调用的更适合微服务的扩展</p>
<p>​	同时可以应对秒杀活动中[应对高并发写请求](# 6、应对高并发的写请求)，比如kafka在毫秒延迟基础上可以实现10w级吞吐量</p>
<p>​	针对<a href="#IOT%E6%B5%81%E9%87%8F%E6%B4%AA%E5%B3%B0">IOT流量洪峰</a>做了一些特殊的优化，保证消息的及时性</p>
<p>​	同时可以使用消息队列保证分布式系统<a href="#7%E3%80%81%E5%A6%82%E4%BD%95%E4%BF%9D%E8%AF%81%E6%95%B0%E6%8D%AE%E4%B8%80%E8%87%B4%E6%80%A7">最终一致性</a></p>
<p><strong>分库分表</strong></p>
<p>​		分库分表，可能到了最后数据库层面还是免不了抗高并发的要求，好吧，那么就 将一个数据库拆分为多个库，多个库来扛更高的并发；然后将一个表拆分为多个 表，每个表的数据量保持少一点，提高 sql 跑的性能。<strong>在通讯录、订单和商城商品模块超过千万级别都应及时考虑分表分库</strong></p>
<p><strong>读写分离</strong></p>
<p>​		读写分离，这个就是说大部分时候数据库可能也是读多写少，没必要所有请求都 集中在一个库上吧，可以搞个主从架构，主库写入，从库读取，搞一个读写分离。 读流量太多的时候，还可以加更多的从库。比如<strong>统计监控类的微服务</strong>通过读写分离，只需访问从库就可以完成统计，例如ES</p>
<p><strong>ElasticSearch</strong></p>
<p>​		Elasticsearch，简称 es。es 是分布式的，可以随便扩容，分布式天然就可以支撑高并发，因为动不动就可以扩容加机器来扛更高的并发。那么一些比较简单的<strong>查询、统计类</strong>的操作，比如<strong>运营平台上</strong>的各地市的汇聚统计，还有一些<strong>全文搜索类</strong>的操作，比如<strong>通讯录和订单</strong>的查询。</p>
<h2 id="2、商城系统-亿级商品如何存储"><a href="#2、商城系统-亿级商品如何存储" class="headerlink" title="2、商城系统-亿级商品如何存储"></a>2、商城系统-亿级商品如何存储</h2><p>基于 Hash 取模、一致性 Hash 实现分库分表</p>
<p>高并发读可以通过<a href="5%E3%80%81%E5%BA%94%E5%AF%B9%E9%AB%98%E5%B9%B6%E5%8F%91%E7%9A%84%E8%AF%BB%E8%AF%B7%E6%B1%82">多级缓存</a>应对</p>
<p>大促销热key读的问题通过<a href="**4%E3%80%81%E7%83%ADkey%E9%97%AE%E9%A2%98%E5%A6%82%E4%BD%95%E8%A7%A3%E5%86%B3%EF%BC%9F**">redis集群+本地缓存+限流+key加随机值</a>分布在多个实例中</p>
<p>高并发写的问题通过<strong>基于 Hash 取模、一致性 Hash 实现分库分表</strong>均匀落盘</p>
<p>业务分配不均导致的<strong>热key</strong>读写问题，可以根据业务场景进行range分片，将热点范围下的子key打散</p>
<p>具体实现：预先设定主键的生成规则，根据规则进行数据的分片路由，但这种方式会侵入商品各条线主数据的业务规则，更好的方式是基于<strong>分片元数据服务器</strong>（即每次访问分片前先询问分片元服务器在路由到实际分片）不过会带来复杂性，比如保证元数据服务器的<strong>一致性</strong>和可用性。</p>
<h2 id="3、对账系统-分布式事务一致性"><a href="#3、对账系统-分布式事务一致性" class="headerlink" title="3、对账系统-分布式事务一致性"></a>3、对账系统-分布式事务一致性</h2><blockquote>
<p>尽量避免分布式事务，单进程用数据库事务，跨进程用消息队列</p>
</blockquote>
<p>主流实现分布式系统事务一致性的方案：</p>
<ol>
<li><strong>最终一致性</strong>：也就是基于 MQ 的可靠消息投递的机制，</li>
<li>基于重试加确认的的<strong>最大努力通知方案</strong>。</li>
</ol>
<p>理论上也可以使用（2PC两阶段提交、3PC三阶段提交、TCC短事务、SAGA长事务方案），但是这些方案工业上落地代价很大，不适合互联网的业界场景。针对金融支付等需要强一致性的场景可以通过前两种方案实现。（<strong>展开说的话参考分布式事务</strong>）</p>
<p><img src="https://tva1.sinaimg.cn/large/008eGmZEly1goruh4oifej30xq0auq7p.jpg" alt="image-20210321212516364"></p>
<p>本地数据库事务原理：<strong>undo log</strong>（原子性） + <strong>redo log</strong>（持久性） + <strong>数据库锁</strong>（原子性&amp;隔离性） + <strong>MVCC</strong>（隔离性）</p>
<p>分布式事务原理：<strong>全局事务协调器（原子性）</strong> + 全局锁（隔离性） + <strong>DB本地事务（原子性、持久性）</strong></p>
<p>一、我们公司账单系统和第三方支付系统对账时，就采用“<strong>自研补偿&#x2F;MQ方案 + 人工介入</strong>”方式</p>
<p>落地的话：方案最“轻”，性能损失最少。可掌控性好，简单易懂，易维护。<br>考虑到分布式事务问题是小概率事件，留有补救余地就行，性能的损失可是实打实的反应在线上每一个请求上</p>
<p>二、也了解到业界比如阿里成熟<strong>Seata AT</strong>模式，平均性能会降低35%以上</p>
<p>我觉得不是特殊的场景不推荐</p>
<p>三、RocketMQ事务消息</p>
<p>听起来挺好挺简单的方案，但它比较挑业务场景，同步性强的处理链路不适合。<br>【重要】要求下游MQ消费方一定能成功消费消息。否则转人工介入处理。<br>【重要】千万记得实现幂等性。</p>
<h2 id="4、用户系统-多线程数据割接"><a href="#4、用户系统-多线程数据割接" class="headerlink" title="4、用户系统-多线程数据割接"></a>4、用户系统-多线程数据割接</h2><p>由于项目需要进行数据割接，保证用户多平台使用用户感知的一致，将广东项目的几百万用户及业务数据按照一定的逻辑灌到社区云平台上，由于依赖了第三方统一认证和省侧crm系统，按照之前系统内割接的方法，通过数据库将用户的唯一标识查出来然后使用多线程向省侧crm系统获取结果。</p>
<p>但是测试的过程中，发现每个线程请求的数据发生了错乱，导致每个请求处理的数据有重复，于是立即停止了脚本，当时怀疑是多线程对资源并发访问导致的，于是把ArrayList 改成了CopyOnWriteArrayList，但是折腾了一晚上，不管怎么修改，线程之间一直有重复数据，叫了一起加班的同事也没看出问题来，和同事估算了一下不使用多线程，大概30-40个小时能跑完，想了下也能接受，本来已经准备放弃了。</p>
<p>不过回到家，我还是用多线程仔细单步模拟了下，整个处理的过程，发现在起线程的时候，有些子线程并没有把分配给他的全部id的list处理完，导致最终状态没更新，新线程又去执行了一遍，然后我尝试通过修改在线程外深拷贝一个List再作为参数传入到子线程里，（后续clear的时候也是clear老的List）果然，整个测试过程中再也没出现过重复处理的情况。</p>
<p>事后，我也深究了下原因：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">if</span>(arrayBuffer.length == <span class="number">99</span>) &#123;</span><br><span class="line"> <span class="type">val</span> <span class="variable">asList</span> <span class="operator">=</span> arrayBuffer.toList</span><br><span class="line"> exec.execute ( openIdInsertMethod(asList) )</span><br><span class="line"> arrayBuffer.clear</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>在一个线程中开启另外一个新线程，则新开线程称为该线程的子线程，子线程初始优先级与父线程相同。不过主线程先启动占用了cpu资源，因此主线程总是优于子线程。然而，即使设置了优先级，也无法保障线程的执行次序。只不过，优先级高的线程获取CPU资源的概率较大，优先级低的并非没机会执行。</p>
<p>所以主线程上的clear操作有可能先执行，那么子线程中未处理完的数据就变成一个空的数组，所以就出现了多个线程出现了重复数据的原因，所以我们要保证的是子线程每次执行完后再进行clear即可。而不是一开始定位的保证ArrayList的安全性。所以将赋值(buffer-&gt;list)操作放在外面去执行后，多线程数据就正常了。</p>
<h2 id="5、秒杀系统场景设计"><a href="#5、秒杀系统场景设计" class="headerlink" title="5、秒杀系统场景设计"></a>5、秒杀系统场景设计</h2><p>[见秒杀项目方案设计](# 二、秒杀项目)</p>
<h2 id="6、统计系统-海量计数"><a href="#6、统计系统-海量计数" class="headerlink" title="6、统计系统-海量计数"></a><strong>6、统计系统-海量计数</strong></h2><p><strong>中小规模的计数服务</strong>（万级）</p>
<p>最常见的计数方案是采用缓存 + DB 的存储方案。当计数变更时，先变更计数 DB，计数加 1，然后再变更计数缓存，修改计数存储的 Memcached 或 Redis。这种方案比较通用且成熟，但在高并发访问场景，支持不够友好。在互联网社交系统中，有些业务的计数变更特别频繁，比如微博 feed 的阅读数，计数的变更次数和访问次数相当，每秒十万到百万级以上的更新量，如果用 DB 存储，会给 DB 带来巨大的压力，DB 就会成为整个计数服务的瓶颈所在。即便采用聚合延迟更新 DB 的方案，由于总量特别大，同时请求均衡分散在大量不同的业务端，巨大的写压力仍然是 DB 的不可承受之重。</p>
<p><strong>大型互联网场景</strong>（百万级）</p>
<p>直接把计数全部存储在 Redis 中，通过 hash 分拆的方式，可以大幅提升计数服务在 Redis 集群的写性能，通过主从复制，在 master 后挂载多个从库，利用读写分离，可以大幅提升计数服务在 Redis 集群的读性能。而且 Redis 有持久化机制，不会丢数据</p>
<p>一方面 Redis 作为通用型存储来存储计数，内存存储效率低。以存储一个 key 为 long 型 id、value 为 4 字节的计数为例，Redis 至少需要 65 个字节左右，不同版本略有差异。但这个计数理论只需要占用 12 个字节即可。内存有效负荷只有 12&#x2F;65&#x3D;18.5%。如果再考虑一个 long 型 id 需要存 4 个不同类型的 4 字节计数，内存有效负荷只有 (8+16)&#x2F;(65*4)&#x3D; 9.2%。</p>
<p>另一方面，Redis 所有数据均存在内存，单存储历史千亿级记录，单份数据拷贝需要 10T 以上，要考虑核心业务上 1 主 3 从，需要 40T 以上的内存，再考虑多 IDC 部署，轻松占用上百 T 内存。就按单机 100G 内存来算，计数服务就要占用上千台大内存服务器。存储成本太高。</p>
<p><strong>微博、微信、抖音</strong>（亿级）</p>
<p>定制数据结构，共享key 紧凑存储，提升计数有效负荷率</p>
<p>超过阈值后数据保存到SSD硬盘，内存里存索引</p>
<p>冷key从SSD硬盘中读取后，放入到LRU队列中</p>
<p>自定义主从复制的方式，海量冷数据异步多线程并发复制</p>
<h2 id="7、系统设计-微软"><a href="#7、系统设计-微软" class="headerlink" title="7、系统设计 - 微软"></a>7、系统设计 - 微软</h2><h3 id="1、需求收集"><a href="#1、需求收集" class="headerlink" title="1、需求收集"></a><strong>1、需求收集</strong></h3><p>确认<strong>使用的对象</strong>（ToC：高并发，ToB：高可用）</p>
<p><strong>系统的服务场景</strong>（<strong>即时通信</strong>：低延迟，<strong>游戏</strong>：高性能，<strong>购物</strong>：秒杀-一致性）</p>
<p><strong>用户量级</strong>（<strong>万级</strong>：双机、<strong>百万</strong>：集群、<strong>亿级</strong>：弹性分布式、容器化编排架构）</p>
<p><strong>百万读</strong>：3主6从，<strong>每个节点的读写高峰 QPS</strong> 可能可以达到每秒 5 万，可以实现15万，30万读性能</p>
<p><strong>亿级读</strong>，通过CDN、静态缓存、JVM缓存等多级缓存来提高读并发</p>
<p><strong>百万写</strong>，通过消息队列削峰填谷，通过hash分拆，水平扩展分布式缓存</p>
<p><strong>亿级写</strong>，redis可以定制数据结构、SSD+内存LRU、冷数据异步多线程复制</p>
<p>持久化，（Mysql）承受量约为 1K的QPS，读写分离提升<strong>读并发</strong>，分库分表提升<strong>写并发</strong></p>
<h3 id="2、顶层设计"><a href="#2、顶层设计" class="headerlink" title="2、顶层设计"></a><strong>2、顶层设计</strong></h3><p>核心功能包括什么：</p>
<p>写功能：发送微博</p>
<p>读功能：热点资讯</p>
<p>交互：点赞、关注</p>
<h3 id="3、系统核心指标"><a href="#3、系统核心指标" class="headerlink" title="3、系统核心指标"></a><strong>3、系统核心指标</strong></h3><ul>
<li>系统<strong>性能</strong>和<strong>延迟</strong><ul>
<li>边缘计算 | 动静分离 | 缓存 |  多线程 |</li>
</ul>
</li>
<li><strong>可扩展性</strong>和<strong>吞吐量</strong><ul>
<li>负载均衡 | 水平扩展 | 垂直扩展 | 异步 | 批处理 | 读写分离</li>
</ul>
</li>
<li><strong>可用性</strong>和<strong>一致性</strong><ul>
<li>主从复制 | 哨兵模式 | 集群 | 分布式事务</li>
</ul>
</li>
</ul>
<h3 id="4、数据存储"><a href="#4、数据存储" class="headerlink" title="4、数据存储"></a>4、数据存储</h3><p>键值存储 : Redis ( 热点资讯 )</p>
<p>文档存储 : MongoDB ( 微博文档分类)</p>
<p>分词倒排：Elasticsearch（搜索）</p>
<p>列型存储：Hbase、BigTable（大数据）</p>
<p>图形存储：Neo4j （社交及推荐）</p>
<p>多媒体：FastDfs（图文视频微博）</p>
<h2 id="7、如何设计一个微博"><a href="#7、如何设计一个微博" class="headerlink" title="7、如何设计一个微博"></a>7、如何设计一个微博</h2><p><strong>实现哪些功能：</strong></p>
<p>筛选出核心功能（Post a Tweet，Timeline，News Feed，Follow&#x2F;Unfollow a user，Register&#x2F;Login）</p>
<p><strong>承担多大QPS：</strong></p>
<p>QPS &#x3D; 100，那么用我的笔记本作Web服务器就好了</p>
<p>QPS &#x3D; 1K，一台好点的Web 服务器也能应付，需要考虑单点故障；</p>
<p>QPS &#x3D; 1m，则需要建设一个1000台Web服务器的集群，考虑动态扩容、负载分担、故障转移</p>
<p>一台 SQL Database （Mysql）承受量约为 1K的QPS；</p>
<p>一台 NoSQL Database (Redis) 约承受量是 20k 的 QPS；</p>
<p>一台 NoSQL Database (Memcache) 约承受量是 200k 的 QPS；</p>
<p><strong>微服务战略拆分</strong></p>
<img src="https://tva1.sinaimg.cn/large/008eGmZEly1goruqql81gj30p20c5q45.jpg" alt="img" style="zoom:67%;" />

<p><strong>针对不同服务选择不同存储</strong></p>
<p><img src="https://pic1.zhimg.com/80/v2-13cab4d5f56e3ecb682c351c0eb4a24b_1440w.jpg?source=1940ef5c" alt="img"></p>
<p><strong>设计数据表的结构</strong></p>
<p><img src="https://tva1.sinaimg.cn/large/008eGmZEly1goruu4homyj31400ht405.jpg" alt="img"></p>
<p>基本差不多就形成了一个解决方案，但是并不是完美的，仍然需要小步快跑的不断的针对<strong>消息队列、缓存、分布式事务、分表分库、大数据、监控、可伸缩</strong>方面进行优化</p>
<h1 id="八、领域模型落地"><a href="#八、领域模型落地" class="headerlink" title="八、领域模型落地"></a>八、领域模型落地</h1><h3 id="1、拆分微服务"><a href="#1、拆分微服务" class="headerlink" title="1、拆分微服务"></a>1、拆分微服务</h3><blockquote>
<p>​	微服务内高内聚，微服务间低耦合</p>
</blockquote>
<p><strong>微服务内高内聚</strong>即单一职责原则</p>
<p>​	每个微服务中的代码变化都是同一类原因。因这类原因而需要变更的代码都在这个微服务中，与其他微服务无关，那么就可以将代码修改的范围缩小到这个微服务内。把这个微服务修改好了，独立修改、独立发布，该需求就实现了。这样，微服务的优势才能发挥出来。</p>
<p><strong>微服务间低耦合</strong>开放封闭原则</p>
<p>​	就是说在微服务实现自身业务的过程中，如果需要执行的某些过程不是自己的职责，就应当将这些过程交给其他微服务去实现，你只需要对它的接口进行调用。这样，微服务之间的调用就实现了解耦。</p>
<p>​	<strong>领域建模</strong>就是将一个系统划分成了多个子域，每个子域都是一个独立的业务场景，每个子域的边界就是“<strong>限界上下文</strong>”。该业务场景会涉及许多领域对象，但<strong>分析建模</strong>始终需要围绕着业务场景的上下文进行。</p>
<p>​	<strong>领域事件通知机制</strong>最有效的方式就是通过消息队列，实现领域事件在微服务间的通知。</p>
<blockquote>
<p>“核心通讯录”微服务只负责发送变更消息到消息队列，不管谁会接收并处理这些消息；</p>
<p>“门禁管理”微服务只负责接收照片变更消息，不管谁发送的这个消息。</p>
</blockquote>
<h3 id="2、关联微服务"><a href="#2、关联微服务" class="headerlink" title="2、关联微服务"></a>2、关联微服务</h3><ol>
<li><p>按照<strong>限界上下文</strong>进行微服务的拆分，将领域模型<strong>划分到多个问题子域</strong></p>
</li>
<li><p>基于<strong>充血模型</strong>与<strong>贫血模型</strong>设计各个微服务的业务领域层（Service、Entity、Value）</p>
</li>
<li><p>通过<strong>领域事件通知机制</strong>和<strong>微服务调用</strong>的推拉结合，将各个子域进行解耦关联</p>
<ul>
<li><strong>核心</strong>：</li>
</ul>
</li>
</ol>
<ul>
<li><p>通讯录 | 短信 | 推送通知 | 支付 | 文件服务</p>
</li>
<li><p><strong>智慧通行</strong></p>
<blockquote>
<p>解决物业多品牌、多系统应用造成的<strong>信息孤岛</strong>，<strong>数据混乱</strong>的问题</p>
</blockquote>
<ul>
<li>人脸门禁 | 可视对讲 | 电梯梯控 | 停车系统 | 访客预约</li>
</ul>
</li>
<li><p><strong>安全社区</strong></p>
<blockquote>
<p>通过<strong>图像视频识别</strong>、<strong>传感数据采集</strong>，实现<strong>报警联动</strong>和<strong>风险预警</strong></p>
</blockquote>
<ul>
<li>视频监控 | 周界报警 | 高空抛物 | 跨域追踪</li>
</ul>
</li>
<li><p><strong>全屋智能</strong></p>
<blockquote>
<p>围绕业主需求，逐步引入社区医疗、社区养老、<strong>社区团购</strong>、<strong>社区家政</strong>等服务</p>
</blockquote>
<ul>
<li>超级面板 | 无线门锁 | 烟感雾感</li>
</ul>
</li>
<li><p><strong>增值服务</strong></p>
<blockquote>
<p>实现跨品牌的产品体验，支持基于<strong>matrix引擎</strong>的智能生活场景裂变能力</p>
</blockquote>
<ul>
<li>智能充电 | 云广播 | 出入提醒 | 定向投放</li>
</ul>
</li>
</ul>
<h3 id="3、微服务的落地"><a href="#3、微服务的落地" class="headerlink" title="3、微服务的落地"></a><strong>3、微服务的落地</strong></h3><blockquote>
<p>​	通过合理的微服务设计，尽量让每次的需求变更都交给某个小团队独立完成，让需求变更落到某个微服务上进行变更。唯有这样，每次变更只需独立地修改这个微服务，独立打包、独立升级，新需求独立实现，才能发挥微服务的优势。</p>
</blockquote>
<ul>
<li><p><strong>数据隔离：</strong>数据库中用户信息表的读写只有<strong>通讯录</strong>微服务。当其他微服务需要读写用户信息时，就不能直接读取用户信息表，而是通过 API 接口去调用<strong>通讯录</strong>微服务。</p>
</li>
<li><p><strong>接口复用：</strong>因此，当多个团队向你提需求时，必须要对这些接口进行规划，通过复用<strong>尽可能少的接口满足他们的需求；</strong>当有新的接口提出时，要尽量通过现有接口解决问题。</p>
</li>
<li><p><strong>向前兼容：</strong>当调用方需要接口变更时怎么办？变更现有接口应当尽可能向前兼容，即接口的名称与参数都不变，只是在内部增加新的功能。<strong>宁愿增加一个新的接口也最好不要去变更原有的接口。</strong></p>
</li>
<li><p><strong>本地调用：</strong>在<strong>访客申请</strong>微服务的本地，增加一个<strong>查询用户Service</strong>的 feign 接口。这样，<strong>访客申请Service</strong>就像本地调用一样调用<strong>查询用户Service</strong>，再通过 feign 接口实现远程调用。这种<strong>防腐层</strong>的设计，可以隔离当前微服务以外的其他微服务拆分变更导致的接口的失效的影响。</p>
</li>
<li><p><strong>数据库去中心化：</strong></p>
<ul>
<li>微服务中<strong>通讯录服务</strong>与<strong>健康码服务</strong>分别对应的<strong>用户库与权限库</strong>，它们的共同特点是数据量小但频繁读取，可以选用小型的 MySQL 数据库并在前面架设 Redis 来提高查询性能；</li>
<li>微服务中<strong>访客通行</strong>与<strong>生活缴费</strong>分别对应的<strong>通行记录库、订单库</strong>，其特点是数据量大并且高并发写，选用一个数据库显然扛不住这样的压力，因此可以选用了 TiDB 这样的 NewSQL 数据库进行分布式存储，将数据压力分散到多个数据节点中，从而解决 I&#x2F;O 瓶颈；</li>
<li>微服务中<strong>数据分析</strong>与<strong>通讯录查询</strong>这样的查询分析业务，则选用 <strong>NoSQL 数据库</strong>或<strong>大数据平台</strong>，通过读写分离将生产库上的数据同步过来进行分布式存储，然后宽表一系列的预处理，应对海量历史数据的决策分析与秒级查询。（ NoSQL 为空的字段是不占用空间的，因此字段再多都不影响查询性能）</li>
</ul>
</li>
</ul>
<h3 id="4、领域模型的意义"><a href="#4、领域模型的意义" class="headerlink" title="4、领域模型的意义"></a>4、领域模型的意义</h3><p>​	<strong>贫血模型、充血模型、策略模式、装饰者模式</strong>只是DDD实现的方式，而DDD的真谛是<strong>领域建模</strong>。</p>
<p>​	做事不能仅凭一腔热血，一定要符合自然规律。其实软件的设计开发过程也是这样。对业务理解不深刻全局架构设计往往是过度设计，这时候<strong>应该抓主要流程</strong>，开始领域建模。</p>
<ul>
<li>接着，每次添加新功能的时候，一方面要满足当前的需求，另一方面业务相关的<strong>领域建模设计</strong>刚刚满足需求，从而使设计最简化、代码最少。</li>
<li>这样的设计过程叫<strong>小步快跑</strong>。采用小步快跑的设计方法，一开始不用思考那么多问题，从简单问题开始逐步深入。<strong>领域模型</strong>就像小树一样一点儿一点儿成长，最后完成所有的功能。</li>
</ul>
<blockquote>
<p>保持软件设计不退化的关键在于每次需求变更的设计，只有保证每次需求变更时做出正确的设计，才能保证软件以一种良性循环的方式不断维护下去。</p>
</blockquote>
<p>​	有没有一种方法，让我们在第十次变更、第二十次变更、第三十次变更时，依然能够找到正确的设计呢？有，那就是<strong>领域驱动设计</strong></p>
<p>​	那么在每次需求变更时，将变更还原到真实世界中，看看真实世界是什么样子的，根据真实世界进行变更。</p>
<h3 id="5、战略建模"><a href="#5、战略建模" class="headerlink" title="5、战略建模"></a>5、战略建模</h3><p>​	<img src="https://tva1.sinaimg.cn/large/008i3skNly1gq6jet6kizj310c0ngtp4.jpg" alt="image-20210504174616848" style="zoom:50%;" /></p>
<h3 id="6、相关名词"><a href="#6、相关名词" class="headerlink" title="6、相关名词"></a><strong>6、相关名词</strong></h3><p><strong>领域和子域（Domain&#x2F;Subdomain）</strong></p>
<p>​	在<strong>上下文地图</strong>构建的领域中，对应模块，使用<strong>限界上下文</strong>划分领域，对应微服务</p>
<p><strong>限界上下文（Bounded Context）</strong></p>
<p>​	在一个领域&#x2F;子域中，有概念上的领域边界，任何<strong>领域对象</strong>在该边界内部的有不依赖外部的确切含义。</p>
<p><strong>领域对象</strong></p>
<p>​	服务、实体与值对象是领域驱动设计的领域对象，可以通过<strong>贫血模型</strong>和<strong>充血模型</strong>转换为程序设计</p>
<p><strong>实体和值对象</strong></p>
<p>​	通过一个<strong>唯一标识字段来区分</strong>真实世界中的每一个个体的领域对象，称为实体。真实世界中那些<strong>一成不变的</strong>、本质性的事物的领域对象，称为值对象。	<strong>可变性</strong>是实体的特点，而<strong>不变性</strong>则是值对象的本质。</p>
<p><strong>贫血模型与充血模型</strong></p>
<p>​	POJO对象中只保存get&#x2F;set方法，没有任何业务逻辑，这样的设计被称为<strong>贫血模型</strong></p>
<p>​	<strong>充血模型</strong>是封装和继承思想的体现，门禁设备实体中，包含特征值下发、广告下发、通行记录回调等方法，不同厂商的实体针对多态进行<strong>聚合</strong>，并通过<strong>工厂或仓库</strong>对外提供服务。在充血模型中， Service 只干一件非常简单的事，就是直接去调用对象中的<strong>工厂方法</strong>生成不同产品，其他的什么都不干。</p>
<p><strong>聚合</strong></p>
<p>​	聚合体现的是一种<strong>整体与部分</strong>的关系。正是因为有这样的关系，在操作整体的时候，整体就封装了对部分的操作。如何正确理解是否存在聚合的关系：就是当<strong>整体不存在</strong>时，部分就变得<strong>没有了意义</strong>。部分是整体的一个部分，与<strong>整体有相同的生命周期</strong>。</p>
<p><strong>工厂</strong></p>
<p><strong>通过装配，创建领域对象，是领域对象生命周期的起点。</strong>譬如，系统要通过 ID 装载一个访客申请：</p>
<ol>
<li><p>表单工厂分别调用表单信息DAO、表单明细 DAO 和用户DAO 去进行查询；</p>
</li>
<li><p>将得到的表单明细对象、用户对象进行装配，分别 set 到<strong>表单信息对象</strong>的<strong>表单明细</strong>与<strong>用户属性</strong>中；</p>
</li>
<li><p>最后，表单工厂将装配好的表单对象返回给表单仓库。</p>
</li>
</ol>
<p><strong>仓库</strong></p>
<p>​	如果服务器是一个非常强大的服务器，那么我们不需要任何数据库。系统创建的所有领域对象都放在仓库中，当需要这些对象时，通过 ID 到仓库中去获取。</p>
<ul>
<li><p>当客户程序通过 ID 去获取某个领域对象时，仓库会通过这个 ID 先到<strong>缓存中进行查找</strong>：</p>
</li>
<li><p>查找到了，则<strong>直接返回</strong>，不需要查询数据库；</p>
</li>
<li><p>没有找到，则通知工厂，工厂调用 DAO 去数据库中查询，然后<strong>装配成领域对象返回给仓库</strong>。</p>
</li>
<li><p>仓库在收到这个领域对象以后，在返回给客户程序的同时，将该<strong>对象放到缓存中</strong></p>
</li>
</ul>

    

    
    <div class="page-reward">
      <a href="javascript:void(0);" class="page-reward-btn tooltip-top" target="_self">
        <div class="tooltip tooltip-east">
          <span class="tooltip-item">
            赏
          </span>
          <span class="tooltip-content">
            <span class="tooltip-text">
              <span class="tooltip-inner">
                <p class="reward-p"><i class="icon icon-quo-left"></i>谢谢你请我吃糖果<i
                    class="icon icon-quo-right"></i></p>
                <div class="reward-box">
                  
                  <div class="reward-box-item">
                    <img class="reward-img" src="/img/alipay.png">
                    <span class="reward-type">支付宝</span>
                  </div>
                  
                  
                  <div class="reward-box-item">
                    <img class="reward-img" src="/img/weixin.png">
                    <span class="reward-type">微信</span>
                  </div>
                  
                </div>
              </span>
            </span>
          </span>
        </div>
      </a>
    </div>
    

    

  </div>
  <div class="article-info article-info-index">
    
    
	<div class="article-tag tagcloud">
		<i class="icon-price-tags icon"></i>
		<ul class="article-tag-list">
			 
        		<li class="article-tag-list-item">
        			<a href="javascript:void(0)" class="js-tag article-tag-list-link color3">面经</a>
        		</li>
      		 
        		<li class="article-tag-list-item">
        			<a href="javascript:void(0)" class="js-tag article-tag-list-link color4">面试题</a>
        		</li>
      		 
        		<li class="article-tag-list-item">
        			<a href="javascript:void(0)" class="js-tag article-tag-list-link color5">系统设计</a>
        		</li>
      		
		</ul>
	</div>

    

    

    
    
<div class="share-btn share-icons tooltip-left">
  <div class="tooltip tooltip-east">
    <span class="tooltip-item">
      <a href="javascript:;" class="share-sns share-outer">
        <i class="icon icon-share"></i>
      </a>
    </span>
    <span class="tooltip-content">
      <div class="share-wrap">
        <div class="share-icons">
          <a class="weibo share-sns" href="javascript:;" data-type="weibo">
            <i class="icon icon-weibo"></i>
          </a>
          <!-- <a class="weixin share-sns wxFab" href="javascript:;" data-type="weixin">
            <i class="icon icon-weixin"></i>
          </a> -->
          <a class="qq share-sns" href="javascript:;" data-type="qq">
            <i class="icon icon-qq"></i>
          </a>
          <a class="douban share-sns" href="javascript:;" data-type="douban">
            <i class="icon icon-douban"></i>
          </a>
          <a class="qzone share-sns" href="javascript:;" data-type="qzone">
            <i class="icon icon-qzone"></i>
          </a>
          <a class="facebook share-sns" href="javascript:;" data-type="facebook">
            <i class="icon icon-facebook"></i>
          </a>
          <a class="twitter share-sns" href="javascript:;" data-type="twitter">
            <i class="icon icon-twitter"></i>
          </a>
          <a class="google share-sns" href="javascript:;" data-type="google">
            <i class="icon icon-google"></i>
          </a>
        </div>
      </div>
    </span>
  </div>
</div>

<div class="page-modal wx-share js-wx-box">
    <a class="close js-modal-close" href="javascript:;"><i class="icon icon-close"></i></a>
    <p>扫一扫，分享到微信</p>
    <div class="wx-qrcode">
     <!-- <img src="//pan.baidu.com/share/qrcode?url=https://blog.elfred.top/2022/05/21/internet/DESIGN/" alt="微信分享二维码"> -->
    </div>
</div>

<div class="mask js-mask"></div>

    
    <div class="clearfix"></div>
  </div>
  </div>
</article>


<nav id="article-nav">
  
    <a href="/2022/05/21/interview/Spring%E5%B8%B8%E8%A7%81%E9%9D%A2%E8%AF%95%E9%A2%98/" id="article-nav-newer" class="article-nav-link-wrap">
      <i class="icon-circle-left"></i>
      <div class="article-nav-title">
        
          Spring常见面试题
        
      </div>
    </a>
  
  
    <a href="/2022/05/21/internet/JAVA/" id="article-nav-older" class="article-nav-link-wrap">
      <div class="article-nav-title">那些年我们背过的JAVA面试题</div>
      <i class="icon-circle-right"></i>
    </a>
  
</nav>


<aside class="wrap-side-operation">
    <div class="mod-side-operation">
        
        <div class="jump-container" id="js-jump-container" style="display:none;">
            <a href="javascript:void(0)" class="mod-side-operation__jump-to-top">
                <i class="icon-font icon-back"></i>
            </a>
            <div id="js-jump-plan-container" class="jump-plan-container" style="top: -11px;">
                <i class="icon-font icon-plane jump-plane"></i>
            </div>
        </div>
        
        
        <div class="toc-container tooltip-left">
            <i class="icon-font icon-category"></i>
            <div class="tooltip tooltip-east">
                <span class="tooltip-item">
                </span>
                <span class="tooltip-content">
                    <div class="toc-article">
                    <ol class="toc"><li class="toc-item toc-level-1"><a class="toc-link" href="#%E4%B8%80%E3%80%81ES%E7%AF%87"><span class="toc-number">1.</span> <span class="toc-text">一、ES篇</span></a><ol class="toc-child"><li class="toc-item toc-level-2"><a class="toc-link" href="#1%E3%80%81%E6%A6%82%E8%BF%B0"><span class="toc-number">1.1.</span> <span class="toc-text">1、概述</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#%E7%89%B9%E7%82%B9"><span class="toc-number">1.1.1.</span> <span class="toc-text">特点</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E5%8A%9F%E8%83%BD"><span class="toc-number">1.1.2.</span> <span class="toc-text">功能</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E5%9C%BA%E6%99%AF"><span class="toc-number">1.1.3.</span> <span class="toc-text">场景</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E7%AB%9E%E5%93%81%E5%88%86%E6%9E%90"><span class="toc-number">1.1.4.</span> <span class="toc-text">竞品分析</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E5%AF%B9%E6%AF%94"><span class="toc-number">1.1.5.</span> <span class="toc-text">对比</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#2%E3%80%81%E5%9F%BA%E6%9C%AC%E6%A6%82%E5%BF%B5"><span class="toc-number">1.2.</span> <span class="toc-text">2、基本概念</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#IK%E5%88%86%E8%AF%8D%E5%99%A8"><span class="toc-number">1.2.1.</span> <span class="toc-text">IK分词器</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E7%B4%A2%E5%BC%95%EF%BC%88%E7%B1%BB%E6%95%B0%E6%8D%AE%E5%BA%93%EF%BC%89"><span class="toc-number">1.2.2.</span> <span class="toc-text">索引（类数据库）</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E6%98%A0%E5%B0%84%EF%BC%88%E7%B1%BB%E8%A1%A8%E8%AE%BE%E8%AE%A1%EF%BC%89"><span class="toc-number">1.2.3.</span> <span class="toc-text">映射（类表设计）</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E6%96%87%E6%A1%A3%EF%BC%88%E6%95%B0%E6%8D%AE%EF%BC%89"><span class="toc-number">1.2.4.</span> <span class="toc-text">文档（数据）</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#3%E3%80%81%E9%AB%98%E7%BA%A7%E7%89%B9%E6%80%A7"><span class="toc-number">1.3.</span> <span class="toc-text">3、高级特性</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#%E6%98%A0%E5%B0%84%E9%AB%98%E7%BA%A7"><span class="toc-number">1.3.1.</span> <span class="toc-text">映射高级</span></a><ol class="toc-child"><li class="toc-item toc-level-4"><a class="toc-link" href="#%E5%9C%B0%E7%90%86%E5%9D%90%E6%A0%87%E7%82%B9%E6%95%B0%E6%8D%AE%E7%B1%BB%E5%9E%8B"><span class="toc-number">1.3.1.1.</span> <span class="toc-text">地理坐标点数据类型</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#%E5%8A%A8%E6%80%81%E6%98%A0%E5%B0%84"><span class="toc-number">1.3.1.2.</span> <span class="toc-text">动态映射</span></a></li></ol></li><li class="toc-item toc-level-3"><a class="toc-link" href="#DSL%E9%AB%98%E7%BA%A7"><span class="toc-number">1.3.2.</span> <span class="toc-text">DSL高级</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E8%81%9A%E5%90%88%E5%88%86%E6%9E%90"><span class="toc-number">1.3.3.</span> <span class="toc-text">聚合分析</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E6%99%BA%E8%83%BD%E6%90%9C%E7%B4%A2"><span class="toc-number">1.3.4.</span> <span class="toc-text">智能搜索</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#4%E3%80%81%E5%AE%9E%E6%88%98"><span class="toc-number">1.4.</span> <span class="toc-text">4、实战</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#%E5%86%99%E4%BC%98%E5%8C%96"><span class="toc-number">1.4.1.</span> <span class="toc-text">写优化</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E8%AF%BB%E4%BC%98%E5%8C%96"><span class="toc-number">1.4.2.</span> <span class="toc-text">读优化</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E9%9B%B6%E5%81%9C%E6%9C%BA%E7%B4%A2%E5%BC%95%E9%87%8D%E5%BB%BA%E6%96%B9%E6%A1%88"><span class="toc-number">1.4.3.</span> <span class="toc-text">零停机索引重建方案</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#DeepPaging%E6%80%A7%E8%83%BD%E8%A7%A3%E5%86%B3%E6%96%B9%E6%A1%88"><span class="toc-number">1.4.4.</span> <span class="toc-text">DeepPaging性能解决方案</span></a></li></ol></li></ol></li><li class="toc-item toc-level-1"><a class="toc-link" href="#%E4%BA%8C%EF%BC%9ADocker-amp-K8S%E7%AF%87"><span class="toc-number">2.</span> <span class="toc-text">二：Docker&amp;K8S篇</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#Why-Docker"><span class="toc-number">2.0.1.</span> <span class="toc-text">Why Docker</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E6%A0%B8%E5%BF%83%E6%A6%82%E5%BF%B5"><span class="toc-number">2.0.2.</span> <span class="toc-text">核心概念</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E5%9F%BA%E6%9C%AC%E6%93%8D%E4%BD%9C"><span class="toc-number">2.0.3.</span> <span class="toc-text">基本操作</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E5%AE%9E%E6%88%98"><span class="toc-number">2.0.4.</span> <span class="toc-text">实战</span></a></li></ol></li></ol></li><li class="toc-item toc-level-1"><a class="toc-link" href="#%E4%B8%89%E3%80%81Netty%E7%AF%87"><span class="toc-number">3.</span> <span class="toc-text">三、Netty篇</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#%E6%A0%B8%E5%BF%83%E7%BB%84%E4%BB%B6"><span class="toc-number">3.0.1.</span> <span class="toc-text">核心组件</span></a><ol class="toc-child"><li class="toc-item toc-level-4"><a class="toc-link" href="#1%E3%80%81%E6%95%B4%E4%BD%93%E7%BB%93%E6%9E%84"><span class="toc-number">3.0.1.1.</span> <span class="toc-text">1、整体结构</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#2%E3%80%81%E9%80%BB%E8%BE%91%E6%9E%B6%E6%9E%84"><span class="toc-number">3.0.1.2.</span> <span class="toc-text">2、逻辑架构</span></a></li></ol></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E7%BD%91%E7%BB%9C%E4%BC%A0%E8%BE%93"><span class="toc-number">3.0.2.</span> <span class="toc-text">网络传输</span></a><ol class="toc-child"><li class="toc-item toc-level-4"><a class="toc-link" href="#1%E3%80%81%E4%BA%94%E7%A7%8DIO%E6%A8%A1%E5%9E%8B%E7%9A%84%E5%8C%BA%E5%88%AB"><span class="toc-number">3.0.2.1.</span> <span class="toc-text">1、五种IO模型的区别</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#2%E3%80%81Reactor%E5%A4%9A%E7%BA%BF%E7%A8%8B%E6%A8%A1%E5%9E%8B"><span class="toc-number">3.0.2.2.</span> <span class="toc-text">2、Reactor多线程模型</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#3%E3%80%81%E6%8B%86%E5%8C%85%E7%B2%98%E5%8C%85%E9%97%AE%E9%A2%98"><span class="toc-number">3.0.2.3.</span> <span class="toc-text">3、拆包粘包问题</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#4%E3%80%81%E8%87%AA%E5%AE%9A%E4%B9%89%E5%8D%8F%E8%AE%AE"><span class="toc-number">3.0.2.4.</span> <span class="toc-text">4、自定义协议</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#5%E3%80%81WriteAndFlush"><span class="toc-number">3.0.2.5.</span> <span class="toc-text">5、WriteAndFlush</span></a></li></ol></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E5%86%85%E5%AD%98%E7%AE%A1%E7%90%86"><span class="toc-number">3.0.3.</span> <span class="toc-text">内存管理</span></a><ol class="toc-child"><li class="toc-item toc-level-4"><a class="toc-link" href="#1%E3%80%81%E5%A0%86%E5%A4%96%E5%86%85%E5%AD%98"><span class="toc-number">3.0.3.1.</span> <span class="toc-text">1、堆外内存</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#2%E3%80%81%E6%95%B0%E6%8D%AE%E8%BD%BD%E4%BD%93ByteBuf"><span class="toc-number">3.0.3.2.</span> <span class="toc-text">2、数据载体ByteBuf</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#3%E3%80%81%E5%86%85%E5%AD%98%E5%88%86%E9%85%8Djemalloc"><span class="toc-number">3.0.3.3.</span> <span class="toc-text">3、内存分配jemalloc</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#4%E3%80%81jemalloc-%E6%9E%B6%E6%9E%84"><span class="toc-number">3.0.3.4.</span> <span class="toc-text">4、jemalloc 架构</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#5%E3%80%81%E5%86%85%E5%AD%98%E6%B1%A0%E8%AE%BE%E8%AE%A1%EF%BC%88%E5%BE%85%E8%A1%A5%E5%85%85%EF%BC%89"><span class="toc-number">3.0.3.5.</span> <span class="toc-text">5、内存池设计（待补充）</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#6%E3%80%81Recycle%E5%AF%B9%E8%B1%A1%E6%B1%A0%EF%BC%88%E5%BE%85%E8%A1%A5%E5%85%85%EF%BC%89"><span class="toc-number">3.0.3.6.</span> <span class="toc-text">6、Recycle对象池（待补充）</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#7%E3%80%81%E9%9B%B6%E6%8B%B7%E8%B4%9D%E6%8A%80%E6%9C%AF"><span class="toc-number">3.0.3.7.</span> <span class="toc-text">7、零拷贝技术</span></a></li></ol></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E9%AB%98%E6%80%A7%E8%83%BD%E6%95%B0%E6%8D%AE%E7%BB%93%E6%9E%84"><span class="toc-number">3.0.4.</span> <span class="toc-text">高性能数据结构</span></a><ol class="toc-child"><li class="toc-item toc-level-4"><a class="toc-link" href="#1%E3%80%81FastThreadLocal"><span class="toc-number">3.0.4.1.</span> <span class="toc-text">1、FastThreadLocal</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#2%E3%80%81HashedTimerWheel"><span class="toc-number">3.0.4.2.</span> <span class="toc-text">2、HashedTimerWheel</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#3%E3%80%81MpscQueue"><span class="toc-number">3.0.4.3.</span> <span class="toc-text">3、MpscQueue</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#4%E3%80%81select%E3%80%81poll%E3%80%81epoll%E7%9A%84%E5%8C%BA%E5%88%AB"><span class="toc-number">3.0.4.4.</span> <span class="toc-text">4、select、poll、epoll的区别</span></a></li></ol></li></ol></li></ol></li><li class="toc-item toc-level-1"><a class="toc-link" href="#%E5%9B%9B%E3%80%81LEETCODE"><span class="toc-number">4.</span> <span class="toc-text">四、LEETCODE</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#%E3%80%90Python%E8%AF%AD%E6%B3%95%E3%80%91"><span class="toc-number">4.0.1.</span> <span class="toc-text">【Python语法】</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E3%80%90%E8%83%8C%E5%8C%85%E6%A8%A1%E6%9D%BF%E3%80%91"><span class="toc-number">4.0.2.</span> <span class="toc-text">【背包模板】</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E3%80%90%E5%9B%9E%E6%BA%AF%E6%A8%A1%E6%9D%BF%E3%80%91"><span class="toc-number">4.0.3.</span> <span class="toc-text">【回溯模板】</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E3%80%90%E5%B9%B6%E6%9F%A5%E9%9B%86%E6%A8%A1%E6%9D%BF%E3%80%91"><span class="toc-number">4.0.4.</span> <span class="toc-text">【并查集模板】</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E3%80%90%E6%8B%93%E6%89%91%E6%8E%92%E5%BA%8F%E6%A8%A1%E6%9D%BF%E3%80%91"><span class="toc-number">4.0.5.</span> <span class="toc-text">【拓扑排序模板】</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E3%80%90%E5%8D%95%E8%B0%83%E6%A0%88%E6%A8%A1%E6%9D%BF%E3%80%91"><span class="toc-number">4.0.6.</span> <span class="toc-text">【单调栈模板】</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E3%80%90%E4%BA%8C%E5%88%86%E6%A8%A1%E6%9D%BF%E3%80%91"><span class="toc-number">4.0.7.</span> <span class="toc-text">【二分模板】</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E3%80%90%E5%8A%A8%E6%80%81%E8%A7%84%E5%88%92%E6%A8%A1%E6%9D%BF%E3%80%91"><span class="toc-number">4.0.8.</span> <span class="toc-text">【动态规划模板】</span></a><ol class="toc-child"><li class="toc-item toc-level-4"><a class="toc-link" href="#%E3%80%8C%E5%8D%95%E4%B8%B2%E9%97%AE%E9%A2%98%E3%80%8D"><span class="toc-number">4.0.8.1.</span> <span class="toc-text">「单串问题」</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#%E3%80%8C%E5%8D%95%E4%B8%B2%E5%8A%A0%E7%8A%B6%E6%80%81%E9%97%AE%E9%A2%98%E3%80%8D"><span class="toc-number">4.0.8.2.</span> <span class="toc-text">「单串加状态问题」</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#%E3%80%8C%E7%BB%8F%E5%85%B8%E5%8F%8C%E4%B8%B2LCS%E9%97%AE%E9%A2%98%E3%80%8D"><span class="toc-number">4.0.8.3.</span> <span class="toc-text">「经典双串LCS问题」</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#%E3%80%8C%E5%8C%BA%E9%97%B4%E5%8A%A8%E6%80%81%E8%A7%84%E5%88%92%E3%80%8D"><span class="toc-number">4.0.8.4.</span> <span class="toc-text">「区间动态规划」</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#%E3%80%8C%E5%8C%BA%E9%97%B4%E5%88%86%E6%B2%BB%E5%8A%A8%E6%80%81%E8%A7%84%E5%88%92%E3%80%8D"><span class="toc-number">4.0.8.5.</span> <span class="toc-text">「区间分治动态规划」</span></a></li></ol></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E3%80%90%E6%BB%91%E5%8A%A8%E7%AA%97%E5%8F%A3%E3%80%91"><span class="toc-number">4.0.9.</span> <span class="toc-text">【滑动窗口】</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E3%80%90%E5%89%8D%E7%BC%80%E5%92%8C%E3%80%91"><span class="toc-number">4.0.10.</span> <span class="toc-text">【前缀和】</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E3%80%90%E5%8F%8C%E6%8C%87%E9%92%88%E3%80%91"><span class="toc-number">4.0.11.</span> <span class="toc-text">【双指针】</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E3%80%90%E6%B7%B1%E5%BA%A6%E4%BC%98%E5%85%88%E3%80%91"><span class="toc-number">4.0.12.</span> <span class="toc-text">【深度优先】</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E3%80%90%E5%B9%BF%E5%BA%A6%E4%BC%98%E5%85%88%E3%80%91"><span class="toc-number">4.0.13.</span> <span class="toc-text">【广度优先】</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E3%80%90%E5%9B%BE%E8%AE%BA%E3%80%91"><span class="toc-number">4.0.14.</span> <span class="toc-text">【图论】</span></a></li></ol></li></ol></li><li class="toc-item toc-level-1"><a class="toc-link" href="#%E4%BA%94%E3%80%81%E5%AE%9E%E6%88%98%E7%AE%97%E6%B3%95%E7%AF%87"><span class="toc-number">5.</span> <span class="toc-text">五、实战算法篇</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#1%E3%80%81URL%E9%BB%91%E5%90%8D%E5%8D%95%EF%BC%88%E5%B8%83%E9%9A%86%E8%BF%87%E6%BB%A4%E5%99%A8%EF%BC%89"><span class="toc-number">5.0.1.</span> <span class="toc-text">1、URL黑名单（布隆过滤器）</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#2%E3%80%81%E8%AF%8D%E9%A2%91%E7%BB%9F%E8%AE%A1%EF%BC%88%E5%88%86%E6%96%87%E4%BB%B6%EF%BC%89"><span class="toc-number">5.0.2.</span> <span class="toc-text">2、词频统计（分文件）</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#3%E3%80%81%E6%9C%AA%E5%87%BA%E7%8E%B0%E7%9A%84%E6%95%B0%EF%BC%88bit%E6%95%B0%E7%BB%84%EF%BC%89"><span class="toc-number">5.0.3.</span> <span class="toc-text">3、未出现的数（bit数组）</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#4%E3%80%81%E9%87%8D%E5%A4%8DURL%EF%BC%88%E5%88%86%E6%9C%BA%E5%99%A8%EF%BC%89"><span class="toc-number">5.0.4.</span> <span class="toc-text">4、重复URL（分机器）</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#5%E3%80%81TOPK%E6%90%9C%E7%B4%A2%EF%BC%88%E5%B0%8F%E6%A0%B9%E5%A0%86%EF%BC%89"><span class="toc-number">5.0.5.</span> <span class="toc-text">5、TOPK搜索（小根堆）</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#6%E3%80%81%E4%B8%AD%E4%BD%8D%E6%95%B0%EF%BC%88%E5%8D%95%E5%90%91%E4%BA%8C%E5%88%86%E6%9F%A5%E6%89%BE%EF%BC%89"><span class="toc-number">5.0.6.</span> <span class="toc-text">6、中位数（单向二分查找）</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#7%E3%80%81%E7%9F%AD%E5%9F%9F%E5%90%8D%E7%B3%BB%E7%BB%9F%EF%BC%88%E7%BC%93%E5%AD%98%EF%BC%89"><span class="toc-number">5.0.7.</span> <span class="toc-text">7、短域名系统（缓存）</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#8%E3%80%81%E6%B5%B7%E9%87%8F%E8%AF%84%E8%AE%BA%E5%85%A5%E5%BA%93%EF%BC%88%E6%B6%88%E6%81%AF%E9%98%9F%E5%88%97%EF%BC%89"><span class="toc-number">5.0.8.</span> <span class="toc-text">8、海量评论入库（消息队列）</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#9%E3%80%81%E5%9C%A8%E7%BA%BF-x2F-%E5%B9%B6%E5%8F%91%E7%94%A8%E6%88%B7%E6%95%B0%EF%BC%88Redis%EF%BC%89"><span class="toc-number">5.0.9.</span> <span class="toc-text">9、在线&#x2F;并发用户数（Redis）</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#10%E3%80%81%E7%83%AD%E9%97%A8%E5%AD%97%E7%AC%A6%E4%B8%B2%EF%BC%88%E5%89%8D%E7%BC%80%E6%A0%91%EF%BC%89"><span class="toc-number">5.0.10.</span> <span class="toc-text">10、热门字符串（前缀树）</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#11%E3%80%81%E7%BA%A2%E5%8C%85%E7%AE%97%E6%B3%95"><span class="toc-number">5.0.11.</span> <span class="toc-text">11、红包算法</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#11%E3%80%81%E6%89%8B%E5%86%99%E5%BF%AB%E6%8E%92"><span class="toc-number">5.0.12.</span> <span class="toc-text">11、手写快排</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#12%E3%80%81%E6%89%8B%E5%86%99%E5%BD%92%E5%B9%B6"><span class="toc-number">5.0.13.</span> <span class="toc-text">12、手写归并</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#13%E3%80%81%E6%89%8B%E5%86%99%E5%A0%86%E6%8E%92"><span class="toc-number">5.0.14.</span> <span class="toc-text">13、手写堆排</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#14%E3%80%81%E6%89%8B%E5%86%99%E5%8D%95%E4%BE%8B"><span class="toc-number">5.0.15.</span> <span class="toc-text">14、手写单例</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#15%E3%80%81%E6%89%8B%E5%86%99LRUcache"><span class="toc-number">5.0.16.</span> <span class="toc-text">15、手写LRUcache</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#16%E3%80%81%E6%89%8B%E5%86%99%E7%BA%BF%E7%A8%8B%E6%B1%A0"><span class="toc-number">5.0.17.</span> <span class="toc-text">16、手写线程池</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#17%E3%80%81%E6%89%8B%E5%86%99%E6%B6%88%E8%B4%B9%E8%80%85%E7%94%9F%E4%BA%A7%E8%80%85%E6%A8%A1%E5%BC%8F"><span class="toc-number">5.0.18.</span> <span class="toc-text">17、手写消费者生产者模式</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#18%E3%80%81%E6%89%8B%E5%86%99%E9%98%BB%E5%A1%9E%E9%98%9F%E5%88%97"><span class="toc-number">5.0.19.</span> <span class="toc-text">18、手写阻塞队列</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#19%E3%80%81%E6%89%8B%E5%86%99%E5%A4%9A%E7%BA%BF%E7%A8%8B%E4%BA%A4%E6%9B%BF%E6%89%93%E5%8D%B0ABC"><span class="toc-number">5.0.20.</span> <span class="toc-text">19、手写多线程交替打印ABC</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#20%E3%80%81%E4%BA%A4%E6%9B%BF%E6%89%93%E5%8D%B0FooBar"><span class="toc-number">5.0.21.</span> <span class="toc-text">20、交替打印FooBar</span></a></li></ol></li></ol></li><li class="toc-item toc-level-1"><a class="toc-link" href="#%E5%85%AD%E3%80%81%E4%B8%AA%E4%BA%BA%E9%A1%B9%E7%9B%AE"><span class="toc-number">6.</span> <span class="toc-text">六、个人项目</span></a><ol class="toc-child"><li class="toc-item toc-level-2"><a class="toc-link" href="#%E4%B8%80%E3%80%81%E4%B8%80%E7%AB%99%E5%88%B0%E5%BA%95"><span class="toc-number">6.1.</span> <span class="toc-text">一、一站到底</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#1%E3%80%81%E5%A6%82%E4%BD%95%E8%AE%BE%E8%AE%A1%E6%8E%92%E8%A1%8C%E6%A6%9C"><span class="toc-number">6.1.1.</span> <span class="toc-text">1、如何设计排行榜</span></a><ol class="toc-child"><li class="toc-item toc-level-4"><a class="toc-link" href="#%E6%80%A7%E8%83%BD%E4%BC%98%E5%8C%96%E8%BF%87%E7%A8%8B"><span class="toc-number">6.1.1.1.</span> <span class="toc-text">性能优化过程</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#%E6%96%B9%E6%A1%88%E4%BC%98%E5%8C%96%E8%BF%87%E7%A8%8B"><span class="toc-number">6.1.1.2.</span> <span class="toc-text">方案优化过程</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#%E6%96%B9%E6%A1%881%EF%BC%9A%E6%AF%8F%E6%97%A5%E4%B8%80%E4%B8%AA%E6%BB%9A%E5%8A%A8%E6%A6%9C%EF%BC%8C%E5%BD%93%E6%97%A5%E6%B1%87%E8%81%9A%EF%BC%88%E8%B4%B9%E6%97%B6%E9%97%B4%EF%BC%89"><span class="toc-number">6.1.1.3.</span> <span class="toc-text">方案1：每日一个滚动榜，当日汇聚（费时间）</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#%E6%96%B9%E6%A1%882%EF%BC%9A%E5%85%A8%E5%B1%80N%E4%B8%AA%E6%BB%9A%E5%8A%A8%E6%A6%9C%E5%90%8C%E6%97%B6%E5%86%99%EF%BC%88%E8%B4%B9%E7%A9%BA%E9%97%B4%EF%BC%89"><span class="toc-number">6.1.1.4.</span> <span class="toc-text">方案2：全局N个滚动榜同时写（费空间）</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#%E6%96%B9%E6%A1%883%EF%BC%9A%E5%AE%9E%E6%97%B6%E6%9B%B4%E6%96%B0%EF%BC%8C%E5%B8%B8%E6%95%B0%E6%AC%A1%E5%86%99%E6%93%8D%E4%BD%9C"><span class="toc-number">6.1.1.5.</span> <span class="toc-text">方案3：实时更新，常数次写操作</span></a></li></ol></li><li class="toc-item toc-level-3"><a class="toc-link" href="#2%E3%80%81%E5%A6%82%E4%BD%95%E8%A7%A3%E5%86%B3%E9%87%8D%E5%A4%8D%E7%AD%94%E9%A2%98"><span class="toc-number">6.1.2.</span> <span class="toc-text">2、如何解决重复答题</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#3%E3%80%81%E4%B8%80%E4%B8%AA%E9%A2%98%E7%9B%AE%E8%A2%AB%E5%A4%9A%E4%B8%AA%E4%BA%BA%E6%8A%A2%E7%AD%94"><span class="toc-number">6.1.3.</span> <span class="toc-text">3、一个题目被多个人抢答</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#4%E3%80%81%E5%A6%82%E4%BD%95%E7%AE%A1%E7%90%86%E6%98%B5%E7%A7%B0%E9%87%8D%E5%A4%8D"><span class="toc-number">6.1.4.</span> <span class="toc-text">4、如何管理昵称重复</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#5%E3%80%81%E5%A6%82%E4%BD%95%E7%AE%A1%E7%90%86%E5%87%BA%E9%A2%98%E5%AE%9A%E6%97%B6%E4%BB%BB%E5%8A%A1"><span class="toc-number">6.1.5.</span> <span class="toc-text">5、如何管理出题定时任务</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#6%EF%BC%9A%E5%A6%82%E4%BD%95%E8%A7%A3%E5%86%B3%E5%AE%A2%E6%88%B7%E7%AB%AF%E6%96%AD%E8%BF%9E"><span class="toc-number">6.1.6.</span> <span class="toc-text">6：如何解决客户端断连</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E4%BA%8C%E3%80%81%E7%A7%92%E6%9D%80%E9%A1%B9%E7%9B%AE"><span class="toc-number">6.2.</span> <span class="toc-text">二、秒杀项目</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#%E6%8A%80%E6%9C%AF%E9%80%89%E5%9E%8B"><span class="toc-number">6.2.1.</span> <span class="toc-text">技术选型</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E6%96%B9%E6%A1%88%E8%AE%BE%E8%AE%A1"><span class="toc-number">6.2.2.</span> <span class="toc-text">方案设计</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#1%E3%80%81%E5%A6%82%E4%BD%95%E8%A7%A3%E5%86%B3%E8%B6%85%E5%8D%96%EF%BC%9F"><span class="toc-number">6.2.3.</span> <span class="toc-text">1、如何解决超卖？</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#2%E3%80%81%E5%A6%82%E4%BD%95%E8%A7%A3%E5%86%B3%E9%87%8D%E5%A4%8D%E4%B8%8B%E5%8D%95%EF%BC%9F"><span class="toc-number">6.2.4.</span> <span class="toc-text">2、如何解决重复下单？</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#3%E3%80%81%E5%A6%82%E4%BD%95%E9%98%B2%E5%88%B7%EF%BC%9F"><span class="toc-number">6.2.5.</span> <span class="toc-text">3、如何防刷？</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#4%E3%80%81%E7%83%ADkey%E9%97%AE%E9%A2%98%E5%A6%82%E4%BD%95%E8%A7%A3%E5%86%B3%EF%BC%9F"><span class="toc-number">6.2.6.</span> <span class="toc-text">4、热key问题如何解决？</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#5%E3%80%81%E5%BA%94%E5%AF%B9%E9%AB%98%E5%B9%B6%E5%8F%91%E7%9A%84%E8%AF%BB%E8%AF%B7%E6%B1%82"><span class="toc-number">6.2.7.</span> <span class="toc-text">5、应对高并发的读请求</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#6%E3%80%81%E5%BA%94%E5%AF%B9%E9%AB%98%E5%B9%B6%E5%8F%91%E7%9A%84%E5%86%99%E8%AF%B7%E6%B1%82"><span class="toc-number">6.2.8.</span> <span class="toc-text">6、应对高并发的写请求</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#7%E3%80%81%E5%A6%82%E4%BD%95%E4%BF%9D%E8%AF%81%E6%95%B0%E6%8D%AE%E4%B8%80%E8%87%B4%E6%80%A7"><span class="toc-number">6.2.9.</span> <span class="toc-text">7、如何保证数据一致性</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#8%E3%80%81%E5%8F%AF%E9%9D%A0%E6%80%A7%E5%A6%82%E4%BD%95%E4%BF%9D%E9%9A%9C"><span class="toc-number">6.2.10.</span> <span class="toc-text">8、可靠性如何保障**</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#9%E3%80%81%E7%A7%92%E6%9D%80%E7%B3%BB%E7%BB%9F%E7%93%B6%E9%A2%88-%E6%97%A5%E5%BF%97"><span class="toc-number">6.2.11.</span> <span class="toc-text">9、秒杀系统瓶颈-日志</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E4%B8%89%E3%80%81%E5%8D%B3%E6%97%B6%E9%80%9A%E4%BF%A1"><span class="toc-number">6.3.</span> <span class="toc-text">三、即时通信</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#1%E3%80%81%E5%8D%95%E8%81%8A%E6%B6%88%E6%81%AF%E5%8F%AF%E9%9D%A0%E4%BC%A0%E8%BE%93"><span class="toc-number">6.3.1.</span> <span class="toc-text">1、单聊消息可靠传输</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#2%E3%80%81%E7%BE%A4%E8%81%8A%E6%B6%88%E6%81%AF%E5%A6%82%E4%BD%95%E4%BF%9D%E8%AF%81%E4%B8%8D%E4%B8%A2%E4%B8%8D%E9%87%8D"><span class="toc-number">6.3.2.</span> <span class="toc-text">2、群聊消息如何保证不丢不重</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#3%E3%80%81%E5%A6%82%E4%BD%95%E4%BF%9D%E8%AF%81%E6%B6%88%E6%81%AF%E7%9A%84%E6%97%B6%E5%BA%8F%E6%80%A7"><span class="toc-number">6.3.3.</span> <span class="toc-text">3、如何保证消息的时序性</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#4%EF%BC%9A%E6%8E%A8%E6%8B%89%E7%BB%93%E5%90%88"><span class="toc-number">6.3.4.</span> <span class="toc-text">4：推拉结合</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#5%E3%80%81%E5%A5%BD%E5%8F%8B%E6%8E%A8%E8%8D%90"><span class="toc-number">6.3.5.</span> <span class="toc-text">5、好友推荐</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E5%9B%9B%E3%80%81%E6%99%BA%E6%85%A7%E7%A4%BE%E5%8C%BA"><span class="toc-number">6.4.</span> <span class="toc-text">四、智慧社区</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#%E7%89%A9%E8%81%94%E7%BD%91%E6%9E%B6%E6%9E%84"><span class="toc-number">6.4.1.</span> <span class="toc-text">物联网架构</span></a><ol class="toc-child"><li class="toc-item toc-level-4"><a class="toc-link" href="#DCM%E7%B3%BB%E7%BB%9F%E6%9E%B6%E6%9E%84"><span class="toc-number">6.4.1.1.</span> <span class="toc-text">DCM系统架构</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#%E4%B8%89%E8%A6%81%E7%B4%A0"><span class="toc-number">6.4.1.2.</span> <span class="toc-text">三要素</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#%E4%BA%91-x2F-%E8%BE%B9-x2F-%E7%AB%AF%E5%8D%8F%E5%90%8C"><span class="toc-number">6.4.1.3.</span> <span class="toc-text">云 &#x2F; 边 &#x2F; 端协同</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#%E7%89%A9%E8%81%94%E7%BD%91%E5%B9%B3%E5%8F%B0%E6%8E%A5%E5%85%A5"><span class="toc-number">6.4.1.4.</span> <span class="toc-text">物联网平台接入</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#%E9%97%A8%E9%94%81%E6%8E%A5%E5%85%A5"><span class="toc-number">6.4.1.5.</span> <span class="toc-text">门锁接入</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#%E5%90%84%E7%A7%8D%E5%8D%8F%E8%AE%AE"><span class="toc-number">6.4.1.6.</span> <span class="toc-text">各种协议</span></a></li></ol></li><li class="toc-item toc-level-3"><a class="toc-link" href="#IOT%E6%B5%81%E9%87%8F%E6%B4%AA%E5%B3%B0"><span class="toc-number">6.4.2.</span> <span class="toc-text">IOT流量洪峰</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E7%A4%BE%E5%8C%BA%E7%9B%B4%E6%92%AD%E5%B8%A6%E8%B4%A7"><span class="toc-number">6.4.3.</span> <span class="toc-text">社区直播带货</span></a><ol class="toc-child"><li class="toc-item toc-level-4"><a class="toc-link" href="#%E4%BA%A7%E5%93%81%E7%9A%84%E8%83%8C%E6%99%AF"><span class="toc-number">6.4.3.1.</span> <span class="toc-text">产品的背景</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#%E9%9D%A2%E4%B8%B4%E7%9A%84%E6%8C%91%E6%88%98"><span class="toc-number">6.4.3.2.</span> <span class="toc-text">面临的挑战</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#%E5%8D%8F%E8%AE%AE%E7%9A%84%E6%AF%94%E8%BE%83"><span class="toc-number">6.4.3.3.</span> <span class="toc-text">协议的比较</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#%E6%95%B4%E4%BD%93%E6%B5%81%E7%A8%8B"><span class="toc-number">6.4.3.4.</span> <span class="toc-text">整体流程</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#%E7%9B%B4%E6%92%AD%E6%B5%81%E7%A8%8B"><span class="toc-number">6.4.3.5.</span> <span class="toc-text">直播流程</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#%E6%92%AD%E6%94%BE%E6%B5%81%E7%A8%8B"><span class="toc-number">6.4.3.6.</span> <span class="toc-text">播放流程</span></a></li></ol></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E7%9B%B4%E6%92%AD%E9%AB%98%E5%8F%AF%E7%94%A8%E6%96%B9%E6%A1%88"><span class="toc-number">6.4.4.</span> <span class="toc-text">直播高可用方案</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E6%80%A7%E8%83%BD%E4%BC%98%E5%8C%96%E6%96%B9%E6%A1%88"><span class="toc-number">6.4.5.</span> <span class="toc-text">性能优化方案</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E6%B5%81%E9%87%8F%E5%9B%9E%E6%94%BE%E8%87%AA%E5%8A%A8%E5%8C%96%E6%B5%8B%E8%AF%95"><span class="toc-number">6.4.6.</span> <span class="toc-text">流量回放自动化测试</span></a></li></ol></li></ol></li><li class="toc-item toc-level-1"><a class="toc-link" href="#%E4%B8%83%E3%80%81%E6%9E%B6%E6%9E%84%E8%AE%BE%E8%AE%A1"><span class="toc-number">7.</span> <span class="toc-text">七、架构设计</span></a><ol class="toc-child"><li class="toc-item toc-level-2"><a class="toc-link" href="#1%E3%80%81%E7%A4%BE%E5%8C%BA%E7%B3%BB%E7%BB%9F%E7%9A%84%E6%9E%B6%E6%9E%84"><span class="toc-number">7.1.</span> <span class="toc-text">1、社区系统的架构</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#2%E3%80%81%E5%95%86%E5%9F%8E%E7%B3%BB%E7%BB%9F-%E4%BA%BF%E7%BA%A7%E5%95%86%E5%93%81%E5%A6%82%E4%BD%95%E5%AD%98%E5%82%A8"><span class="toc-number">7.2.</span> <span class="toc-text">2、商城系统-亿级商品如何存储</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#3%E3%80%81%E5%AF%B9%E8%B4%A6%E7%B3%BB%E7%BB%9F-%E5%88%86%E5%B8%83%E5%BC%8F%E4%BA%8B%E5%8A%A1%E4%B8%80%E8%87%B4%E6%80%A7"><span class="toc-number">7.3.</span> <span class="toc-text">3、对账系统-分布式事务一致性</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#4%E3%80%81%E7%94%A8%E6%88%B7%E7%B3%BB%E7%BB%9F-%E5%A4%9A%E7%BA%BF%E7%A8%8B%E6%95%B0%E6%8D%AE%E5%89%B2%E6%8E%A5"><span class="toc-number">7.4.</span> <span class="toc-text">4、用户系统-多线程数据割接</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#5%E3%80%81%E7%A7%92%E6%9D%80%E7%B3%BB%E7%BB%9F%E5%9C%BA%E6%99%AF%E8%AE%BE%E8%AE%A1"><span class="toc-number">7.5.</span> <span class="toc-text">5、秒杀系统场景设计</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#6%E3%80%81%E7%BB%9F%E8%AE%A1%E7%B3%BB%E7%BB%9F-%E6%B5%B7%E9%87%8F%E8%AE%A1%E6%95%B0"><span class="toc-number">7.6.</span> <span class="toc-text">6、统计系统-海量计数</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#7%E3%80%81%E7%B3%BB%E7%BB%9F%E8%AE%BE%E8%AE%A1-%E5%BE%AE%E8%BD%AF"><span class="toc-number">7.7.</span> <span class="toc-text">7、系统设计 - 微软</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#1%E3%80%81%E9%9C%80%E6%B1%82%E6%94%B6%E9%9B%86"><span class="toc-number">7.7.1.</span> <span class="toc-text">1、需求收集</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#2%E3%80%81%E9%A1%B6%E5%B1%82%E8%AE%BE%E8%AE%A1"><span class="toc-number">7.7.2.</span> <span class="toc-text">2、顶层设计</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#3%E3%80%81%E7%B3%BB%E7%BB%9F%E6%A0%B8%E5%BF%83%E6%8C%87%E6%A0%87"><span class="toc-number">7.7.3.</span> <span class="toc-text">3、系统核心指标</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#4%E3%80%81%E6%95%B0%E6%8D%AE%E5%AD%98%E5%82%A8"><span class="toc-number">7.7.4.</span> <span class="toc-text">4、数据存储</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#7%E3%80%81%E5%A6%82%E4%BD%95%E8%AE%BE%E8%AE%A1%E4%B8%80%E4%B8%AA%E5%BE%AE%E5%8D%9A"><span class="toc-number">7.8.</span> <span class="toc-text">7、如何设计一个微博</span></a></li></ol></li><li class="toc-item toc-level-1"><a class="toc-link" href="#%E5%85%AB%E3%80%81%E9%A2%86%E5%9F%9F%E6%A8%A1%E5%9E%8B%E8%90%BD%E5%9C%B0"><span class="toc-number">8.</span> <span class="toc-text">八、领域模型落地</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#1%E3%80%81%E6%8B%86%E5%88%86%E5%BE%AE%E6%9C%8D%E5%8A%A1"><span class="toc-number">8.0.1.</span> <span class="toc-text">1、拆分微服务</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#2%E3%80%81%E5%85%B3%E8%81%94%E5%BE%AE%E6%9C%8D%E5%8A%A1"><span class="toc-number">8.0.2.</span> <span class="toc-text">2、关联微服务</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#3%E3%80%81%E5%BE%AE%E6%9C%8D%E5%8A%A1%E7%9A%84%E8%90%BD%E5%9C%B0"><span class="toc-number">8.0.3.</span> <span class="toc-text">3、微服务的落地</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#4%E3%80%81%E9%A2%86%E5%9F%9F%E6%A8%A1%E5%9E%8B%E7%9A%84%E6%84%8F%E4%B9%89"><span class="toc-number">8.0.4.</span> <span class="toc-text">4、领域模型的意义</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#5%E3%80%81%E6%88%98%E7%95%A5%E5%BB%BA%E6%A8%A1"><span class="toc-number">8.0.5.</span> <span class="toc-text">5、战略建模</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#6%E3%80%81%E7%9B%B8%E5%85%B3%E5%90%8D%E8%AF%8D"><span class="toc-number">8.0.6.</span> <span class="toc-text">6、相关名词</span></a></li></ol></li></ol></li></ol>
                    </div>
                </span>
            </div>
        </div>
        
    </div>
</aside>














          </div>
        </div>
      </div>
      <footer id="footer">
  <div class="outer">
    <div id="footer-info">
    	<div class="footer-left">
    		&copy; 2020-2023 <a href="https://blog.elfred.top/" target="_blank">Elfred</a>
    	</div>
      	<div class="footer-right">
			
			
      		GitHub:<a href="https://github.com/JoeyBling/hexo-theme-yilia-plus" target="_blank">hexo-theme-yilia-plus</a> by Litten
      	</div>
    </div>
  </div>
  
  
	<script src="/lib/busuanzi.pure.js"></script>
	
  
  
	
	<span id="busuanzi_container_site_pv" style="display:none">
		本站总访问量<span id="busuanzi_value_site_pv"></span>次	
	        <span class="post-meta-divider" >|</span>
	</span>
  	<span id="busuanzi_container_site_uv" style='display:none'>
  		本站访客数<span id="busuanzi_value_site_uv"></span>人
  	</span>
  
</footer>

    </div>
    <script>
	var yiliaConfig = {
		mathjax: false,
		isHome: false,
		isPost: true,
		isArchive: false,
		isTag: false,
		isCategory: false,
		open_in_new: true,
		toc_hide_index: true,
		root: "/",
		innerArchive: true,
		showTags: true
	}
</script>

<script>!function(r){function e(t){if(i[t])return i[t].exports;var n=i[t]={exports:{},id:t,loaded:!1};return r[t].call(n.exports,n,n.exports,e),n.loaded=!0,n.exports}var i={};e.m=r,e.c=i,e.p="./",e(0)}([function(t,n,r){r(208),t.exports=r(205)},function(t,n,r){var d=r(3),y=r(46),g=r(26),b=r(27),x=r(47),m="prototype",S=function(t,n,r){var e,i,o,u,c=t&S.F,f=t&S.G,a=t&S.S,s=t&S.P,l=t&S.B,h=f?d:a?d[n]||(d[n]={}):(d[n]||{})[m],v=f?y:y[n]||(y[n]={}),p=v[m]||(v[m]={});for(e in f&&(r=n),r)o=((i=!c&&h&&void 0!==h[e])?h:r)[e],u=l&&i?x(o,d):s&&"function"==typeof o?x(Function.call,o):o,h&&b(h,e,o,t&S.U),v[e]!=o&&g(v,e,u),s&&p[e]!=o&&(p[e]=o)};d.core=y,S.F=1,S.G=2,S.S=4,S.P=8,S.B=16,S.W=32,S.U=64,S.R=128,t.exports=S},function(t,n,r){var e=r(5);t.exports=function(t){if(!e(t))throw TypeError(t+" is not an object!");return t}},function(t,n){var r=t.exports="undefined"!=typeof window&&window.Math==Math?window:"undefined"!=typeof self&&self.Math==Math?self:Function("return this")();"number"==typeof __g&&(__g=r)},function(t,n){t.exports=function(t){try{return!!t()}catch(t){return!0}}},function(t,n){t.exports=function(t){return"object"==typeof t?null!==t:"function"==typeof t}},function(t,n){var r=t.exports="undefined"!=typeof window&&window.Math==Math?window:"undefined"!=typeof self&&self.Math==Math?self:Function("return this")();"number"==typeof __g&&(__g=r)},function(t,n,r){var e=r(118)("wks"),i=r(79),o=r(3).Symbol,u="function"==typeof o;(t.exports=function(t){return e[t]||(e[t]=u&&o[t]||(u?o:i)("Symbol."+t))}).store=e},function(t,n,r){var e=r(49),i=Math.min;t.exports=function(t){return 0<t?i(e(t),9007199254740991):0}},function(t,n){var r={}.hasOwnProperty;t.exports=function(t,n){return r.call(t,n)}},function(t,n,r){t.exports=!r(4)(function(){return 7!=Object.defineProperty({},"a",{get:function(){return 7}}).a})},function(t,n,r){var e=r(2),i=r(174),o=r(53),u=Object.defineProperty;n.f=r(10)?Object.defineProperty:function(t,n,r){if(e(t),n=o(n,!0),e(r),i)try{return u(t,n,r)}catch(t){}if("get"in r||"set"in r)throw TypeError("Accessors not supported!");return"value"in r&&(t[n]=r.value),t}},function(t,n,r){t.exports=!r(20)(function(){return 7!=Object.defineProperty({},"a",{get:function(){return 7}}).a})},function(t,n,r){var e=r(14),i=r(24);t.exports=r(12)?function(t,n,r){return e.f(t,n,i(1,r))}:function(t,n,r){return t[n]=r,t}},function(t,n,r){var e=r(22),i=r(60),o=r(42),u=Object.defineProperty;n.f=r(12)?Object.defineProperty:function(t,n,r){if(e(t),n=o(n,!0),e(r),i)try{return u(t,n,r)}catch(t){}if("get"in r||"set"in r)throw TypeError("Accessors not supported!");return"value"in r&&(t[n]=r.value),t}},function(t,n,r){var e=r(96),i=r(34);t.exports=function(t){return e(i(t))}},function(t,n,r){var e=r(40)("wks"),i=r(25),o=r(6).Symbol,u="function"==typeof o;(t.exports=function(t){return e[t]||(e[t]=u&&o[t]||(u?o:i)("Symbol."+t))}).store=e},function(t,n,r){var e=r(51);t.exports=function(t){return Object(e(t))}},function(t,n){t.exports=function(t){return"object"==typeof t?null!==t:"function"==typeof t}},function(t,n){var r=t.exports={version:"2.6.9"};"number"==typeof __e&&(__e=r)},function(t,n){t.exports=function(t){try{return!!t()}catch(t){return!0}}},function(t,n){t.exports=function(t){if("function"!=typeof t)throw TypeError(t+" is not a function!");return t}},function(t,n,r){var e=r(18);t.exports=function(t){if(!e(t))throw TypeError(t+" is not an object!");return t}},function(t,n){t.exports=!0},function(t,n){t.exports=function(t,n){return{enumerable:!(1&t),configurable:!(2&t),writable:!(4&t),value:n}}},function(t,n){var r=0,e=Math.random();t.exports=function(t){return"Symbol(".concat(void 0===t?"":t,")_",(++r+e).toString(36))}},function(t,n,r){var e=r(11),i=r(75);t.exports=r(10)?function(t,n,r){return e.f(t,n,i(1,r))}:function(t,n,r){return t[n]=r,t}},function(t,n,r){var o=r(3),u=r(26),c=r(30),f=r(79)("src"),e=r(219),i="toString",a=(""+e).split(i);r(46).inspectSource=function(t){return e.call(t)},(t.exports=function(t,n,r,e){var i="function"==typeof r;i&&(c(r,"name")||u(r,"name",n)),t[n]!==r&&(i&&(c(r,f)||u(r,f,t[n]?""+t[n]:a.join(String(n)))),t===o?t[n]=r:e?t[n]?t[n]=r:u(t,n,r):(delete t[n],u(t,n,r)))})(Function.prototype,i,function(){return"function"==typeof this&&this[f]||e.call(this)})},function(t,n,r){var e=r(1),i=r(4),u=r(51),c=/"/g,o=function(t,n,r,e){var i=String(u(t)),o="<"+n;return""!==r&&(o+=" "+r+'="'+String(e).replace(c,"&quot;")+'"'),o+">"+i+"</"+n+">"};t.exports=function(n,t){var r={};r[n]=t(o),e(e.P+e.F*i(function(){var t=""[n]('"');return t!==t.toLowerCase()||3<t.split('"').length}),"String",r)}},function(t,n,r){var e=r(65),i=r(35);t.exports=Object.keys||function(t){return e(t,i)}},function(t,n){var r={}.hasOwnProperty;t.exports=function(t,n){return r.call(t,n)}},function(t,n,r){var e=r(117),i=r(75),o=r(33),u=r(53),c=r(30),f=r(174),a=Object.getOwnPropertyDescriptor;n.f=r(10)?a:function(t,n){if(t=o(t),n=u(n,!0),f)try{return a(t,n)}catch(t){}if(c(t,n))return i(!e.f.call(t,n),t[n])}},function(t,n,r){var e=r(30),i=r(17),o=r(154)("IE_PROTO"),u=Object.prototype;t.exports=Object.getPrototypeOf||function(t){return t=i(t),e(t,o)?t[o]:"function"==typeof t.constructor&&t instanceof t.constructor?t.constructor.prototype:t instanceof Object?u:null}},function(t,n,r){var e=r(116),i=r(51);t.exports=function(t){return e(i(t))}},function(t,n){t.exports=function(t){if(null==t)throw TypeError("Can't call method on  "+t);return t}},function(t,n){t.exports="constructor,hasOwnProperty,isPrototypeOf,propertyIsEnumerable,toLocaleString,toString,valueOf".split(",")},function(t,n){t.exports={}},function(t,n){n.f={}.propertyIsEnumerable},function(t,n,r){var e=r(14).f,i=r(9),o=r(16)("toStringTag");t.exports=function(t,n,r){t&&!i(t=r?t:t.prototype,o)&&e(t,o,{configurable:!0,value:n})}},function(t,n,r){var e=r(40)("keys"),i=r(25);t.exports=function(t){return e[t]||(e[t]=i(t))}},function(t,n,r){var e=r(19),i=r(6),o="__core-js_shared__",u=i[o]||(i[o]={});(t.exports=function(t,n){return u[t]||(u[t]=void 0!==n?n:{})})("versions",[]).push({version:e.version,mode:r(23)?"pure":"global",copyright:"© 2019 Denis Pushkarev (zloirock.ru)"})},function(t,n){var r=Math.ceil,e=Math.floor;t.exports=function(t){return isNaN(t=+t)?0:(0<t?e:r)(t)}},function(t,n,r){var i=r(18);t.exports=function(t,n){if(!i(t))return t;var r,e;if(n&&"function"==typeof(r=t.toString)&&!i(e=r.call(t)))return e;if("function"==typeof(r=t.valueOf)&&!i(e=r.call(t)))return e;if(!n&&"function"==typeof(r=t.toString)&&!i(e=r.call(t)))return e;throw TypeError("Can't convert object to primitive value")}},function(t,n,r){var e=r(6),i=r(19),o=r(23),u=r(44),c=r(14).f;t.exports=function(t){var n=i.Symbol||(i.Symbol=o?{}:e.Symbol||{});"_"==t.charAt(0)||t in n||c(n,t,{value:u.f(t)})}},function(t,n,r){n.f=r(16)},function(t,n){var r={}.toString;t.exports=function(t){return r.call(t).slice(8,-1)}},function(t,n){var r=t.exports={version:"2.6.9"};"number"==typeof __e&&(__e=r)},function(t,n,r){var o=r(21);t.exports=function(e,i,t){if(o(e),void 0===i)return e;switch(t){case 1:return function(t){return e.call(i,t)};case 2:return function(t,n){return e.call(i,t,n)};case 3:return function(t,n,r){return e.call(i,t,n,r)}}return function(){return e.apply(i,arguments)}}},function(t,n,r){"use strict";var e=r(4);t.exports=function(t,n){return!!t&&e(function(){n?t.call(null,function(){},1):t.call(null)})}},function(t,n){var r=Math.ceil,e=Math.floor;t.exports=function(t){return isNaN(t=+t)?0:(0<t?e:r)(t)}},function(t,n,r){var x=r(47),m=r(116),S=r(17),w=r(8),e=r(138);t.exports=function(l,t){var h=1==l,v=2==l,p=3==l,d=4==l,y=6==l,g=5==l||y,b=t||e;return function(t,n,r){for(var e,i,o=S(t),u=m(o),c=x(n,r,3),f=w(u.length),a=0,s=h?b(t,f):v?b(t,0):void 0;a<f;a++)if((g||a in u)&&(i=c(e=u[a],a,o),l))if(h)s[a]=i;else if(i)switch(l){case 3:return!0;case 5:return e;case 6:return a;case 2:s.push(e)}else if(d)return!1;return y?-1:p||d?d:s}}},function(t,n){t.exports=function(t){if(null==t)throw TypeError("Can't call method on  "+t);return t}},function(t,n,r){var i=r(1),o=r(46),u=r(4);t.exports=function(t,n){var r=(o.Object||{})[t]||Object[t],e={};e[t]=n(r),i(i.S+i.F*u(function(){r(1)}),"Object",e)}},function(t,n,r){var i=r(5);t.exports=function(t,n){if(!i(t))return t;var r,e;if(n&&"function"==typeof(r=t.toString)&&!i(e=r.call(t)))return e;if("function"==typeof(r=t.valueOf)&&!i(e=r.call(t)))return e;if(!n&&"function"==typeof(r=t.toString)&&!i(e=r.call(t)))return e;throw TypeError("Can't convert object to primitive value")}},function(t,n,r){var d=r(6),y=r(19),g=r(93),b=r(13),x=r(9),m="prototype",S=function(t,n,r){var e,i,o,u=t&S.F,c=t&S.G,f=t&S.S,a=t&S.P,s=t&S.B,l=t&S.W,h=c?y:y[n]||(y[n]={}),v=h[m],p=c?d:f?d[n]:(d[n]||{})[m];for(e in c&&(r=n),r)(i=!u&&p&&void 0!==p[e])&&x(h,e)||(o=i?p[e]:r[e],h[e]=c&&"function"!=typeof p[e]?r[e]:s&&i?g(o,d):l&&p[e]==o?function(e){var t=function(t,n,r){if(this instanceof e){switch(arguments.length){case 0:return new e;case 1:return new e(t);case 2:return new e(t,n)}return new e(t,n,r)}return e.apply(this,arguments)};return t[m]=e[m],t}(o):a&&"function"==typeof o?g(Function.call,o):o,a&&((h.virtual||(h.virtual={}))[e]=o,t&S.R&&v&&!v[e]&&b(v,e,o)))};S.F=1,S.G=2,S.S=4,S.P=8,S.B=16,S.W=32,S.U=64,S.R=128,t.exports=S},function(t,n,r){var e=r(34);t.exports=function(t){return Object(e(t))}},function(t,n,r){var o=r(196),e=r(1),i=r(118)("metadata"),u=i.store||(i.store=new(r(200))),c=function(t,n,r){var e=u.get(t);if(!e){if(!r)return;u.set(t,e=new o)}var i=e.get(n);if(!i){if(!r)return;e.set(n,i=new o)}return i};t.exports={store:u,map:c,has:function(t,n,r){var e=c(n,r,!1);return void 0!==e&&e.has(t)},get:function(t,n,r){var e=c(n,r,!1);return void 0===e?void 0:e.get(t)},set:function(t,n,r,e){c(r,e,!0).set(t,n)},keys:function(t,n){var r=c(t,n,!1),e=[];return r&&r.forEach(function(t,n){e.push(n)}),e},key:function(t){return void 0===t||"symbol"==typeof t?t:String(t)},exp:function(t){e(e.S,"Reflect",t)}}},function(t,n,r){"use strict";if(r(10)){var g=r(68),b=r(3),x=r(4),m=r(1),S=r(132),e=r(159),h=r(47),w=r(70),i=r(75),_=r(26),o=r(76),u=r(49),O=r(8),E=r(194),c=r(78),f=r(53),a=r(30),M=r(81),P=r(5),v=r(17),p=r(145),j=r(72),F=r(32),A=r(73).f,d=r(161),s=r(79),l=r(7),y=r(50),I=r(120),L=r(119),N=r(162),T=r(82),k=r(125),R=r(77),C=r(137),D=r(166),G=r(11),W=r(31),U=G.f,V=W.f,B=b.RangeError,q=b.TypeError,z=b.Uint8Array,K="ArrayBuffer",H="Shared"+K,J="BYTES_PER_ELEMENT",$="prototype",Y=Array[$],X=e.ArrayBuffer,Q=e.DataView,Z=y(0),tt=y(2),nt=y(3),rt=y(4),et=y(5),it=y(6),ot=I(!0),ut=I(!1),ct=N.values,ft=N.keys,at=N.entries,st=Y.lastIndexOf,lt=Y.reduce,ht=Y.reduceRight,vt=Y.join,pt=Y.sort,dt=Y.slice,yt=Y.toString,gt=Y.toLocaleString,bt=l("iterator"),xt=l("toStringTag"),mt=s("typed_constructor"),St=s("def_constructor"),wt=S.CONSTR,_t=S.TYPED,Ot=S.VIEW,Et="Wrong length!",Mt=y(1,function(t,n){return It(L(t,t[St]),n)}),Pt=x(function(){return 1===new z(new Uint16Array([1]).buffer)[0]}),jt=!!z&&!!z[$].set&&x(function(){new z(1).set({})}),Ft=function(t,n){var r=u(t);if(r<0||r%n)throw B("Wrong offset!");return r},At=function(t){if(P(t)&&_t in t)return t;throw q(t+" is not a typed array!")},It=function(t,n){if(!(P(t)&&mt in t))throw q("It is not a typed array constructor!");return new t(n)},Lt=function(t,n){return Nt(L(t,t[St]),n)},Nt=function(t,n){for(var r=0,e=n.length,i=It(t,e);r<e;)i[r]=n[r++];return i},Tt=function(t,n,r){U(t,n,{get:function(){return this._d[r]}})},kt=function(t){var n,r,e,i,o,u,c=v(t),f=arguments.length,a=1<f?arguments[1]:void 0,s=void 0!==a,l=d(c);if(null!=l&&!p(l)){for(u=l.call(c),e=[],n=0;!(o=u.next()).done;n++)e.push(o.value);c=e}for(s&&2<f&&(a=h(a,arguments[2],2)),n=0,r=O(c.length),i=It(this,r);n<r;n++)i[n]=s?a(c[n],n):c[n];return i},Rt=function(){for(var t=0,n=arguments.length,r=It(this,n);t<n;)r[t]=arguments[t++];return r},Ct=!!z&&x(function(){gt.call(new z(1))}),Dt=function(){return gt.apply(Ct?dt.call(At(this)):At(this),arguments)},Gt={copyWithin:function(t,n){return D.call(At(this),t,n,2<arguments.length?arguments[2]:void 0)},every:function(t){return rt(At(this),t,1<arguments.length?arguments[1]:void 0)},fill:function(t){return C.apply(At(this),arguments)},filter:function(t){return Lt(this,tt(At(this),t,1<arguments.length?arguments[1]:void 0))},find:function(t){return et(At(this),t,1<arguments.length?arguments[1]:void 0)},findIndex:function(t){return it(At(this),t,1<arguments.length?arguments[1]:void 0)},forEach:function(t){Z(At(this),t,1<arguments.length?arguments[1]:void 0)},indexOf:function(t){return ut(At(this),t,1<arguments.length?arguments[1]:void 0)},includes:function(t){return ot(At(this),t,1<arguments.length?arguments[1]:void 0)},join:function(t){return vt.apply(At(this),arguments)},lastIndexOf:function(t){return st.apply(At(this),arguments)},map:function(t){return Mt(At(this),t,1<arguments.length?arguments[1]:void 0)},reduce:function(t){return lt.apply(At(this),arguments)},reduceRight:function(t){return ht.apply(At(this),arguments)},reverse:function(){for(var t,n=this,r=At(n).length,e=Math.floor(r/2),i=0;i<e;)t=n[i],n[i++]=n[--r],n[r]=t;return n},some:function(t){return nt(At(this),t,1<arguments.length?arguments[1]:void 0)},sort:function(t){return pt.call(At(this),t)},subarray:function(t,n){var r=At(this),e=r.length,i=c(t,e);return new(L(r,r[St]))(r.buffer,r.byteOffset+i*r.BYTES_PER_ELEMENT,O((void 0===n?e:c(n,e))-i))}},Wt=function(t,n){return Lt(this,dt.call(At(this),t,n))},Ut=function(t){At(this);var n=Ft(arguments[1],1),r=this.length,e=v(t),i=O(e.length),o=0;if(r<i+n)throw B(Et);for(;o<i;)this[n+o]=e[o++]},Vt={entries:function(){return at.call(At(this))},keys:function(){return ft.call(At(this))},values:function(){return ct.call(At(this))}},Bt=function(t,n){return P(t)&&t[_t]&&"symbol"!=typeof n&&n in t&&String(+n)==String(n)},qt=function(t,n){return Bt(t,n=f(n,!0))?i(2,t[n]):V(t,n)},zt=function(t,n,r){return!(Bt(t,n=f(n,!0))&&P(r)&&a(r,"value"))||a(r,"get")||a(r,"set")||r.configurable||a(r,"writable")&&!r.writable||a(r,"enumerable")&&!r.enumerable?U(t,n,r):(t[n]=r.value,t)};wt||(W.f=qt,G.f=zt),m(m.S+m.F*!wt,"Object",{getOwnPropertyDescriptor:qt,defineProperty:zt}),x(function(){yt.call({})})&&(yt=gt=function(){return vt.call(this)});var Kt=o({},Gt);o(Kt,Vt),_(Kt,bt,Vt.values),o(Kt,{slice:Wt,set:Ut,constructor:function(){},toString:yt,toLocaleString:Dt}),Tt(Kt,"buffer","b"),Tt(Kt,"byteOffset","o"),Tt(Kt,"byteLength","l"),Tt(Kt,"length","e"),U(Kt,xt,{get:function(){return this[_t]}}),t.exports=function(t,l,n,o){var h=t+((o=!!o)?"Clamped":"")+"Array",r="get"+t,u="set"+t,v=b[h],c=v||{},e=v&&F(v),i=!v||!S.ABV,f={},a=v&&v[$],p=function(t,i){U(t,i,{get:function(){return t=i,(n=this._d).v[r](t*l+n.o,Pt);var t,n},set:function(t){return n=i,r=t,e=this._d,o&&(r=(r=Math.round(r))<0?0:255<r?255:255&r),void e.v[u](n*l+e.o,r,Pt);var n,r,e},enumerable:!0})};i?(v=n(function(t,n,r,e){w(t,v,h,"_d");var i,o,u,c,f=0,a=0;if(P(n)){if(!(n instanceof X||(c=M(n))==K||c==H))return _t in n?Nt(v,n):kt.call(v,n);i=n,a=Ft(r,l);var s=n.byteLength;if(void 0===e){if(s%l)throw B(Et);if((o=s-a)<0)throw B(Et)}else if(s<(o=O(e)*l)+a)throw B(Et);u=o/l}else u=E(n),i=new X(o=u*l);for(_(t,"_d",{b:i,o:a,l:o,e:u,v:new Q(i)});f<u;)p(t,f++)}),a=v[$]=j(Kt),_(a,"constructor",v)):x(function(){v(1)})&&x(function(){new v(-1)})&&k(function(t){new v,new v(null),new v(1.5),new v(t)},!0)||(v=n(function(t,n,r,e){var i;return w(t,v,h),P(n)?n instanceof X||(i=M(n))==K||i==H?void 0!==e?new c(n,Ft(r,l),e):void 0!==r?new c(n,Ft(r,l)):new c(n):_t in n?Nt(v,n):kt.call(v,n):new c(E(n))}),Z(e!==Function.prototype?A(c).concat(A(e)):A(c),function(t){t in v||_(v,t,c[t])}),v[$]=a,g||(a.constructor=v));var s=a[bt],d=!!s&&("values"==s.name||null==s.name),y=Vt.values;_(v,mt,!0),_(a,_t,h),_(a,Ot,!0),_(a,St,v),(o?new v(1)[xt]==h:xt in a)||U(a,xt,{get:function(){return h}}),f[h]=v,m(m.G+m.W+m.F*(v!=c),f),m(m.S,h,{BYTES_PER_ELEMENT:l}),m(m.S+m.F*x(function(){c.of.call(v,1)}),h,{from:kt,of:Rt}),J in a||_(a,J,l),m(m.P,h,Gt),R(h),m(m.P+m.F*jt,h,{set:Ut}),m(m.P+m.F*!d,h,Vt),g||a.toString==yt||(a.toString=yt),m(m.P+m.F*x(function(){new v(1).slice()}),h,{slice:Wt}),m(m.P+m.F*(x(function(){return[1,2].toLocaleString()!=new v([1,2]).toLocaleString()})||!x(function(){a.toLocaleString.call([1,2])})),h,{toLocaleString:Dt}),T[h]=d?s:y,g||d||_(a,bt,y)}}else t.exports=function(){}},function(t,n){var r={}.toString;t.exports=function(t){return r.call(t).slice(8,-1)}},function(t,n,r){var e=r(18),i=r(6).document,o=e(i)&&e(i.createElement);t.exports=function(t){return o?i.createElement(t):{}}},function(t,n,r){t.exports=!r(12)&&!r(20)(function(){return 7!=Object.defineProperty(r(59)("div"),"a",{get:function(){return 7}}).a})},function(t,n,r){"use strict";var x=r(23),m=r(54),S=r(66),w=r(13),_=r(36),O=r(98),E=r(38),M=r(104),P=r(16)("iterator"),j=!([].keys&&"next"in[].keys()),F="values",A=function(){return this};t.exports=function(t,n,r,e,i,o,u){O(r,n,e);var c,f,a,s=function(t){if(!j&&t in p)return p[t];switch(t){case"keys":case F:return function(){return new r(this,t)}}return function(){return new r(this,t)}},l=n+" Iterator",h=i==F,v=!1,p=t.prototype,d=p[P]||p["@@iterator"]||i&&p[i],y=d||s(i),g=i?h?s("entries"):y:void 0,b="Array"==n&&p.entries||d;if(b&&((a=M(b.call(new t)))!==Object.prototype&&a.next&&(E(a,l,!0),x||"function"==typeof a[P]||w(a,P,A))),h&&d&&d.name!==F&&(v=!0,y=function(){return d.call(this)}),x&&!u||!j&&!v&&p[P]||w(p,P,y),_[n]=y,_[l]=A,i)if(c={values:h?y:s(F),keys:o?y:s("keys"),entries:g},u)for(f in c)f in p||S(p,f,c[f]);else m(m.P+m.F*(j||v),n,c);return c}},function(t,n,e){var i=e(22),o=e(101),u=e(35),c=e(39)("IE_PROTO"),f=function(){},a="prototype",s=function(){var t,n=e(59)("iframe"),r=u.length;for(n.style.display="none",e(95).appendChild(n),n.src="javascript:",(t=n.contentWindow.document).open(),t.write("<script>document.F=Object<\/script>"),t.close(),s=t.F;r--;)delete s[a][u[r]];return s()};t.exports=Object.create||function(t,n){var r;return null!==t?(f[a]=i(t),r=new f,f[a]=null,r[c]=t):r=s(),void 0===n?r:o(r,n)}},function(t,n,r){var e=r(65),i=r(35).concat("length","prototype");n.f=Object.getOwnPropertyNames||function(t){return e(t,i)}},function(t,n){n.f=Object.getOwnPropertySymbols},function(t,n,r){var u=r(9),c=r(15),f=r(92)(!1),a=r(39)("IE_PROTO");t.exports=function(t,n){var r,e=c(t),i=0,o=[];for(r in e)r!=a&&u(e,r)&&o.push(r);for(;n.length>i;)u(e,r=n[i++])&&(~f(o,r)||o.push(r));return o}},function(t,n,r){t.exports=r(13)},function(t,n,r){var e=r(7)("unscopables"),i=Array.prototype;null==i[e]&&r(26)(i,e,{}),t.exports=function(t){i[e][t]=!0}},function(t,n){t.exports=!1},function(t,n,r){var e=r(79)("meta"),i=r(5),o=r(30),u=r(11).f,c=0,f=Object.isExtensible||function(){return!0},a=!r(4)(function(){return f(Object.preventExtensions({}))}),s=function(t){u(t,e,{value:{i:"O"+ ++c,w:{}}})},l=t.exports={KEY:e,NEED:!1,fastKey:function(t,n){if(!i(t))return"symbol"==typeof t?t:("string"==typeof t?"S":"P")+t;if(!o(t,e)){if(!f(t))return"F";if(!n)return"E";s(t)}return t[e].i},getWeak:function(t,n){if(!o(t,e)){if(!f(t))return!0;if(!n)return!1;s(t)}return t[e].w},onFreeze:function(t){return a&&l.NEED&&f(t)&&!o(t,e)&&s(t),t}}},function(t,n){t.exports=function(t,n,r,e){if(!(t instanceof n)||void 0!==e&&e in t)throw TypeError(r+": incorrect invocation!");return t}},function(t,n,r){var h=r(47),v=r(177),p=r(145),d=r(2),y=r(8),g=r(161),b={},x={};(n=t.exports=function(t,n,r,e,i){var o,u,c,f,a=i?function(){return t}:g(t),s=h(r,e,n?2:1),l=0;if("function"!=typeof a)throw TypeError(t+" is not iterable!");if(p(a)){for(o=y(t.length);l<o;l++)if((f=n?s(d(u=t[l])[0],u[1]):s(t[l]))===b||f===x)return f}else for(c=a.call(t);!(u=c.next()).done;)if((f=v(c,s,u.value,n))===b||f===x)return f}).BREAK=b,n.RETURN=x},function(t,n,e){var i=e(2),o=e(183),u=e(141),c=e(154)("IE_PROTO"),f=function(){},a="prototype",s=function(){var t,n=e(140)("iframe"),r=u.length;for(n.style.display="none",e(143).appendChild(n),n.src="javascript:",(t=n.contentWindow.document).open(),t.write("<script>document.F=Object<\/script>"),t.close(),s=t.F;r--;)delete s[a][u[r]];return s()};t.exports=Object.create||function(t,n){var r;return null!==t?(f[a]=i(t),r=new f,f[a]=null,r[c]=t):r=s(),void 0===n?r:o(r,n)}},function(t,n,r){var e=r(185),i=r(141).concat("length","prototype");n.f=Object.getOwnPropertyNames||function(t){return e(t,i)}},function(t,n,r){var e=r(185),i=r(141);t.exports=Object.keys||function(t){return e(t,i)}},function(t,n){t.exports=function(t,n){return{enumerable:!(1&t),configurable:!(2&t),writable:!(4&t),value:n}}},function(t,n,r){var i=r(27);t.exports=function(t,n,r){for(var e in n)i(t,e,n[e],r);return t}},function(t,n,r){"use strict";var e=r(3),i=r(11),o=r(10),u=r(7)("species");t.exports=function(t){var n=e[t];o&&n&&!n[u]&&i.f(n,u,{configurable:!0,get:function(){return this}})}},function(t,n,r){var e=r(49),i=Math.max,o=Math.min;t.exports=function(t,n){return(t=e(t))<0?i(t+n,0):o(t,n)}},function(t,n){var r=0,e=Math.random();t.exports=function(t){return"Symbol(".concat(void 0===t?"":t,")_",(++r+e).toString(36))}},function(t,n,r){var e=r(5);t.exports=function(t,n){if(!e(t)||t._t!==n)throw TypeError("Incompatible receiver, "+n+" required!");return t}},function(t,n,r){var i=r(45),o=r(7)("toStringTag"),u="Arguments"==i(function(){return arguments}());t.exports=function(t){var n,r,e;return void 0===t?"Undefined":null===t?"Null":"string"==typeof(r=function(t,n){try{return t[n]}catch(t){}}(n=Object(t),o))?r:u?i(n):"Object"==(e=i(n))&&"function"==typeof n.callee?"Arguments":e}},function(t,n){t.exports={}},function(t,n,r){var e=r(11).f,i=r(30),o=r(7)("toStringTag");t.exports=function(t,n,r){t&&!i(t=r?t:t.prototype,o)&&e(t,o,{configurable:!0,value:n})}},function(t,n,r){var u=r(1),e=r(51),c=r(4),f=r(157),i="["+f+"]",o=RegExp("^"+i+i+"*"),a=RegExp(i+i+"*$"),s=function(t,n,r){var e={},i=c(function(){return!!f[t]()||"​"!="​"[t]()}),o=e[t]=i?n(l):f[t];r&&(e[r]=o),u(u.P+u.F*i,"String",e)},l=s.trim=function(t,n){return t=String(e(t)),1&n&&(t=t.replace(o,"")),2&n&&(t=t.replace(a,"")),t};t.exports=s},function(t,n,r){t.exports={default:r(88),__esModule:!0}},function(t,n,r){t.exports={default:r(89),__esModule:!0}},function(t,n,r){"use strict";function e(t){return t&&t.__esModule?t:{default:t}}n.__esModule=!0;var i=e(r(86)),o=e(r(85)),u="function"==typeof o.default&&"symbol"==typeof i.default?function(t){return typeof t}:function(t){return t&&"function"==typeof o.default&&t.constructor===o.default&&t!==o.default.prototype?"symbol":typeof t};n.default="function"==typeof o.default&&"symbol"===u(i.default)?function(t){return void 0===t?"undefined":u(t)}:function(t){return t&&"function"==typeof o.default&&t.constructor===o.default&&t!==o.default.prototype?"symbol":void 0===t?"undefined":u(t)}},function(t,n,r){r(111),r(109),r(112),r(113),t.exports=r(19).Symbol},function(t,n,r){r(110),r(114),t.exports=r(44).f("iterator")},function(t,n){t.exports=function(t){if("function"!=typeof t)throw TypeError(t+" is not a function!");return t}},function(t,n){t.exports=function(){}},function(t,n,r){var f=r(15),a=r(107),s=r(106);t.exports=function(c){return function(t,n,r){var e,i=f(t),o=a(i.length),u=s(r,o);if(c&&n!=n){for(;u<o;)if((e=i[u++])!=e)return!0}else for(;u<o;u++)if((c||u in i)&&i[u]===n)return c||u||0;return!c&&-1}}},function(t,n,r){var o=r(90);t.exports=function(e,i,t){if(o(e),void 0===i)return e;switch(t){case 1:return function(t){return e.call(i,t)};case 2:return function(t,n){return e.call(i,t,n)};case 3:return function(t,n,r){return e.call(i,t,n,r)}}return function(){return e.apply(i,arguments)}}},function(t,n,r){var c=r(29),f=r(64),a=r(37);t.exports=function(t){var n=c(t),r=f.f;if(r)for(var e,i=r(t),o=a.f,u=0;i.length>u;)o.call(t,e=i[u++])&&n.push(e);return n}},function(t,n,r){var e=r(6).document;t.exports=e&&e.documentElement},function(t,n,r){var e=r(58);t.exports=Object("z").propertyIsEnumerable(0)?Object:function(t){return"String"==e(t)?t.split(""):Object(t)}},function(t,n,r){var e=r(58);t.exports=Array.isArray||function(t){return"Array"==e(t)}},function(t,n,r){"use strict";var e=r(62),i=r(24),o=r(38),u={};r(13)(u,r(16)("iterator"),function(){return this}),t.exports=function(t,n,r){t.prototype=e(u,{next:i(1,r)}),o(t,n+" Iterator")}},function(t,n){t.exports=function(t,n){return{value:n,done:!!t}}},function(t,n,r){var e=r(25)("meta"),i=r(18),o=r(9),u=r(14).f,c=0,f=Object.isExtensible||function(){return!0},a=!r(20)(function(){return f(Object.preventExtensions({}))}),s=function(t){u(t,e,{value:{i:"O"+ ++c,w:{}}})},l=t.exports={KEY:e,NEED:!1,fastKey:function(t,n){if(!i(t))return"symbol"==typeof t?t:("string"==typeof t?"S":"P")+t;if(!o(t,e)){if(!f(t))return"F";if(!n)return"E";s(t)}return t[e].i},getWeak:function(t,n){if(!o(t,e)){if(!f(t))return!0;if(!n)return!1;s(t)}return t[e].w},onFreeze:function(t){return a&&l.NEED&&f(t)&&!o(t,e)&&s(t),t}}},function(t,n,r){var u=r(14),c=r(22),f=r(29);t.exports=r(12)?Object.defineProperties:function(t,n){c(t);for(var r,e=f(n),i=e.length,o=0;o<i;)u.f(t,r=e[o++],n[r]);return t}},function(t,n,r){var e=r(37),i=r(24),o=r(15),u=r(42),c=r(9),f=r(60),a=Object.getOwnPropertyDescriptor;n.f=r(12)?a:function(t,n){if(t=o(t),n=u(n,!0),f)try{return a(t,n)}catch(t){}if(c(t,n))return i(!e.f.call(t,n),t[n])}},function(t,n,r){var e=r(15),i=r(63).f,o={}.toString,u="object"==typeof window&&window&&Object.getOwnPropertyNames?Object.getOwnPropertyNames(window):[];t.exports.f=function(t){return u&&"[object Window]"==o.call(t)?function(t){try{return i(t)}catch(t){return u.slice()}}(t):i(e(t))}},function(t,n,r){var e=r(9),i=r(55),o=r(39)("IE_PROTO"),u=Object.prototype;t.exports=Object.getPrototypeOf||function(t){return t=i(t),e(t,o)?t[o]:"function"==typeof t.constructor&&t instanceof t.constructor?t.constructor.prototype:t instanceof Object?u:null}},function(t,n,r){var f=r(41),a=r(34);t.exports=function(c){return function(t,n){var r,e,i=String(a(t)),o=f(n),u=i.length;return o<0||u<=o?c?"":void 0:(r=i.charCodeAt(o))<55296||56319<r||o+1===u||(e=i.charCodeAt(o+1))<56320||57343<e?c?i.charAt(o):r:c?i.slice(o,o+2):e-56320+(r-55296<<10)+65536}}},function(t,n,r){var e=r(41),i=Math.max,o=Math.min;t.exports=function(t,n){return(t=e(t))<0?i(t+n,0):o(t,n)}},function(t,n,r){var e=r(41),i=Math.min;t.exports=function(t){return 0<t?i(e(t),9007199254740991):0}},function(t,n,r){"use strict";var e=r(91),i=r(99),o=r(36),u=r(15);t.exports=r(61)(Array,"Array",function(t,n){this._t=u(t),this._i=0,this._k=n},function(){var t=this._t,n=this._k,r=this._i++;return!t||r>=t.length?(this._t=void 0,i(1)):i(0,"keys"==n?r:"values"==n?t[r]:[r,t[r]])},"values"),o.Arguments=o.Array,e("keys"),e("values"),e("entries")},function(t,n){},function(t,n,r){"use strict";var e=r(105)(!0);r(61)(String,"String",function(t){this._t=String(t),this._i=0},function(){var t,n=this._t,r=this._i;return r>=n.length?{value:void 0,done:!0}:(t=e(n,r),this._i+=t.length,{value:t,done:!1})})},function(t,n,r){"use strict";var e=r(6),u=r(9),i=r(12),o=r(54),c=r(66),f=r(100).KEY,a=r(20),s=r(40),l=r(38),h=r(25),v=r(16),p=r(44),d=r(43),y=r(94),g=r(97),b=r(22),x=r(18),m=r(55),S=r(15),w=r(42),_=r(24),O=r(62),E=r(103),M=r(102),P=r(64),j=r(14),F=r(29),A=M.f,I=j.f,L=E.f,N=e.Symbol,T=e.JSON,k=T&&T.stringify,R="prototype",C=v("_hidden"),D=v("toPrimitive"),G={}.propertyIsEnumerable,W=s("symbol-registry"),U=s("symbols"),V=s("op-symbols"),B=Object[R],q="function"==typeof N&&!!P.f,z=e.QObject,K=!z||!z[R]||!z[R].findChild,H=i&&a(function(){return 7!=O(I({},"a",{get:function(){return I(this,"a",{value:7}).a}})).a})?function(t,n,r){var e=A(B,n);e&&delete B[n],I(t,n,r),e&&t!==B&&I(B,n,e)}:I,J=function(t){var n=U[t]=O(N[R]);return n._k=t,n},$=q&&"symbol"==typeof N.iterator?function(t){return"symbol"==typeof t}:function(t){return t instanceof N},Y=function(t,n,r){return t===B&&Y(V,n,r),b(t),n=w(n,!0),b(r),u(U,n)?(r.enumerable?(u(t,C)&&t[C][n]&&(t[C][n]=!1),r=O(r,{enumerable:_(0,!1)})):(u(t,C)||I(t,C,_(1,{})),t[C][n]=!0),H(t,n,r)):I(t,n,r)},X=function(t,n){b(t);for(var r,e=y(n=S(n)),i=0,o=e.length;i<o;)Y(t,r=e[i++],n[r]);return t},Q=function(t){var n=G.call(this,t=w(t,!0));return!(this===B&&u(U,t)&&!u(V,t))&&(!(n||!u(this,t)||!u(U,t)||u(this,C)&&this[C][t])||n)},Z=function(t,n){if(t=S(t),n=w(n,!0),t!==B||!u(U,n)||u(V,n)){var r=A(t,n);return!r||!u(U,n)||u(t,C)&&t[C][n]||(r.enumerable=!0),r}},tt=function(t){for(var n,r=L(S(t)),e=[],i=0;r.length>i;)u(U,n=r[i++])||n==C||n==f||e.push(n);return e},nt=function(t){for(var n,r=t===B,e=L(r?V:S(t)),i=[],o=0;e.length>o;)!u(U,n=e[o++])||r&&!u(B,n)||i.push(U[n]);return i};q||(c((N=function(){if(this instanceof N)throw TypeError("Symbol is not a constructor!");var n=h(0<arguments.length?arguments[0]:void 0),r=function(t){this===B&&r.call(V,t),u(this,C)&&u(this[C],n)&&(this[C][n]=!1),H(this,n,_(1,t))};return i&&K&&H(B,n,{configurable:!0,set:r}),J(n)})[R],"toString",function(){return this._k}),M.f=Z,j.f=Y,r(63).f=E.f=tt,r(37).f=Q,P.f=nt,i&&!r(23)&&c(B,"propertyIsEnumerable",Q,!0),p.f=function(t){return J(v(t))}),o(o.G+o.W+o.F*!q,{Symbol:N});for(var rt="hasInstance,isConcatSpreadable,iterator,match,replace,search,species,split,toPrimitive,toStringTag,unscopables".split(","),et=0;rt.length>et;)v(rt[et++]);for(var it=F(v.store),ot=0;it.length>ot;)d(it[ot++]);o(o.S+o.F*!q,"Symbol",{for:function(t){return u(W,t+="")?W[t]:W[t]=N(t)},keyFor:function(t){if(!$(t))throw TypeError(t+" is not a symbol!");for(var n in W)if(W[n]===t)return n},useSetter:function(){K=!0},useSimple:function(){K=!1}}),o(o.S+o.F*!q,"Object",{create:function(t,n){return void 0===n?O(t):X(O(t),n)},defineProperty:Y,defineProperties:X,getOwnPropertyDescriptor:Z,getOwnPropertyNames:tt,getOwnPropertySymbols:nt});var ut=a(function(){P.f(1)});o(o.S+o.F*ut,"Object",{getOwnPropertySymbols:function(t){return P.f(m(t))}}),T&&o(o.S+o.F*(!q||a(function(){var t=N();return"[null]"!=k([t])||"{}"!=k({a:t})||"{}"!=k(Object(t))})),"JSON",{stringify:function(t){for(var n,r,e=[t],i=1;arguments.length>i;)e.push(arguments[i++]);if(r=n=e[1],(x(n)||void 0!==t)&&!$(t))return g(n)||(n=function(t,n){if("function"==typeof r&&(n=r.call(this,t,n)),!$(n))return n}),e[1]=n,k.apply(T,e)}}),N[R][D]||r(13)(N[R],D,N[R].valueOf),l(N,"Symbol"),l(Math,"Math",!0),l(e.JSON,"JSON",!0)},function(t,n,r){r(43)("asyncIterator")},function(t,n,r){r(43)("observable")},function(t,n,r){r(108);for(var e=r(6),i=r(13),o=r(36),u=r(16)("toStringTag"),c="CSSRuleList,CSSStyleDeclaration,CSSValueList,ClientRectList,DOMRectList,DOMStringList,DOMTokenList,DataTransferItemList,FileList,HTMLAllCollection,HTMLCollection,HTMLFormElement,HTMLSelectElement,MediaList,MimeTypeArray,NamedNodeMap,NodeList,PaintRequestList,Plugin,PluginArray,SVGLengthList,SVGNumberList,SVGPathSegList,SVGPointList,SVGStringList,SVGTransformList,SourceBufferList,StyleSheetList,TextTrackCueList,TextTrackList,TouchList".split(","),f=0;f<c.length;f++){var a=c[f],s=e[a],l=s&&s.prototype;l&&!l[u]&&i(l,u,a),o[a]=o.Array}},function(t,n,r){"use strict";var e=r(2);t.exports=function(){var t=e(this),n="";return t.global&&(n+="g"),t.ignoreCase&&(n+="i"),t.multiline&&(n+="m"),t.unicode&&(n+="u"),t.sticky&&(n+="y"),n}},function(t,n,r){var e=r(45);t.exports=Object("z").propertyIsEnumerable(0)?Object:function(t){return"String"==e(t)?t.split(""):Object(t)}},function(t,n){n.f={}.propertyIsEnumerable},function(t,n,r){var e=r(46),i=r(3),o="__core-js_shared__",u=i[o]||(i[o]={});(t.exports=function(t,n){return u[t]||(u[t]=void 0!==n?n:{})})("versions",[]).push({version:e.version,mode:r(68)?"pure":"global",copyright:"© 2019 Denis Pushkarev (zloirock.ru)"})},function(t,n,r){var i=r(2),o=r(21),u=r(7)("species");t.exports=function(t,n){var r,e=i(t).constructor;return void 0===e||null==(r=i(e)[u])?n:o(r)}},function(t,n,r){var f=r(33),a=r(8),s=r(78);t.exports=function(c){return function(t,n,r){var e,i=f(t),o=a(i.length),u=s(r,o);if(c&&n!=n){for(;u<o;)if((e=i[u++])!=e)return!0}else for(;u<o;u++)if((c||u in i)&&i[u]===n)return c||u||0;return!c&&-1}}},function(t,n,r){"use strict";var g=r(3),b=r(1),x=r(27),m=r(76),S=r(69),w=r(71),_=r(70),O=r(5),E=r(4),M=r(125),P=r(83),j=r(144);t.exports=function(e,t,n,r,i,o){var u=g[e],c=u,f=i?"set":"add",a=c&&c.prototype,s={},l=function(t){var r=a[t];x(a,t,"delete"==t?function(t){return!(o&&!O(t))&&r.call(this,0===t?0:t)}:"has"==t?function(t){return!(o&&!O(t))&&r.call(this,0===t?0:t)}:"get"==t?function(t){return o&&!O(t)?void 0:r.call(this,0===t?0:t)}:"add"==t?function(t){return r.call(this,0===t?0:t),this}:function(t,n){return r.call(this,0===t?0:t,n),this})};if("function"==typeof c&&(o||a.forEach&&!E(function(){(new c).entries().next()}))){var h=new c,v=h[f](o?{}:-0,1)!=h,p=E(function(){h.has(1)}),d=M(function(t){new c(t)}),y=!o&&E(function(){for(var t=new c,n=5;n--;)t[f](n,n);return!t.has(-0)});d||(((c=t(function(t,n){_(t,c,e);var r=j(new u,t,c);return null!=n&&w(n,i,r[f],r),r})).prototype=a).constructor=c),(p||y)&&(l("delete"),l("has"),i&&l("get")),(y||v)&&l(f),o&&a.clear&&delete a.clear}else c=r.getConstructor(t,e,i,f),m(c.prototype,n),S.NEED=!0;return P(c,e),s[e]=c,b(b.G+b.W+b.F*(c!=u),s),o||r.setStrong(c,e,i),c}},function(t,n,r){"use strict";r(197);var s=r(27),l=r(26),h=r(4),v=r(51),p=r(7),d=r(152),y=p("species"),g=!h(function(){var t=/./;return t.exec=function(){var t=[];return t.groups={a:"7"},t},"7"!=="".replace(t,"$<a>")}),b=function(){var t=/(?:)/,n=t.exec;t.exec=function(){return n.apply(this,arguments)};var r="ab".split(t);return 2===r.length&&"a"===r[0]&&"b"===r[1]}();t.exports=function(r,t,n){var e=p(r),o=!h(function(){var t={};return t[e]=function(){return 7},7!=""[r](t)}),i=o?!h(function(){var t=!1,n=/a/;return n.exec=function(){return t=!0,null},"split"===r&&(n.constructor={},n.constructor[y]=function(){return n}),n[e](""),!t}):void 0;if(!o||!i||"replace"===r&&!g||"split"===r&&!b){var u=/./[e],c=n(v,e,""[r],function(t,n,r,e,i){return n.exec===d?o&&!i?{done:!0,value:u.call(n,r,e)}:{done:!0,value:t.call(r,n,e)}:{done:!1}}),f=c[0],a=c[1];s(String.prototype,r,f),l(RegExp.prototype,e,2==t?function(t,n){return a.call(t,this,n)}:function(t){return a.call(t,this)})}}},function(t,n,r){var e=r(45);t.exports=Array.isArray||function(t){return"Array"==e(t)}},function(t,n,r){var e=r(5),i=r(45),o=r(7)("match");t.exports=function(t){var n;return e(t)&&(void 0!==(n=t[o])?!!n:"RegExp"==i(t))}},function(t,n,r){var o=r(7)("iterator"),u=!1;try{var e=[7][o]();e.return=function(){u=!0},Array.from(e,function(){throw 2})}catch(t){}t.exports=function(t,n){if(!n&&!u)return!1;var r=!1;try{var e=[7],i=e[o]();i.next=function(){return{done:r=!0}},e[o]=function(){return i},t(e)}catch(t){}return r}},function(t,n,r){"use strict";t.exports=r(68)||!r(4)(function(){var t=Math.random();__defineSetter__.call(null,t,function(){}),delete r(3)[t]})},function(t,n){n.f=Object.getOwnPropertySymbols},function(t,n,r){"use strict";var i=r(81),o=RegExp.prototype.exec;t.exports=function(t,n){var r=t.exec;if("function"==typeof r){var e=r.call(t,n);if("object"!=typeof e)throw new TypeError("RegExp exec method returned something other than an Object or null");return e}if("RegExp"!==i(t))throw new TypeError("RegExp#exec called on incompatible receiver");return o.call(t,n)}},function(t,n,r){"use strict";var e=r(1),u=r(21),c=r(47),f=r(71);t.exports=function(t){e(e.S,t,{from:function(t){var n,r,e,i,o=arguments[1];return u(this),(n=void 0!==o)&&u(o),null==t?new this:(r=[],n?(e=0,i=c(o,arguments[2],2),f(t,!1,function(t){r.push(i(t,e++))})):f(t,!1,r.push,r),new this(r))}})}},function(t,n,r){"use strict";var e=r(1);t.exports=function(t){e(e.S,t,{of:function(){for(var t=arguments.length,n=new Array(t);t--;)n[t]=arguments[t];return new this(n)}})}},function(t,n,r){var f=r(49),a=r(51);t.exports=function(c){return function(t,n){var r,e,i=String(a(t)),o=f(n),u=i.length;return o<0||u<=o?c?"":void 0:(r=i.charCodeAt(o))<55296||56319<r||o+1===u||(e=i.charCodeAt(o+1))<56320||57343<e?c?i.charAt(o):r:c?i.slice(o,o+2):e-56320+(r-55296<<10)+65536}}},function(t,n,r){for(var e,i=r(3),o=r(26),u=r(79),c=u("typed_array"),f=u("view"),a=!(!i.ArrayBuffer||!i.DataView),s=a,l=0,h="Int8Array,Uint8Array,Uint8ClampedArray,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array".split(",");l<9;)(e=i[h[l++]])?(o(e.prototype,c,!0),o(e.prototype,f,!0)):s=!1;t.exports={ABV:a,CONSTR:s,TYPED:c,VIEW:f}},function(t,n,r){var e=r(3).navigator;t.exports=e&&e.userAgent||""},function(t,n){"use strict";var r,e={versions:(r=window.navigator.userAgent,{trident:-1<r.indexOf("Trident"),presto:-1<r.indexOf("Presto"),webKit:-1<r.indexOf("AppleWebKit"),gecko:-1<r.indexOf("Gecko")&&-1==r.indexOf("KHTML"),mobile:!!r.match(/AppleWebKit.*Mobile.*/),ios:!!r.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/),android:-1<r.indexOf("Android")||-1<r.indexOf("Linux"),iPhone:-1<r.indexOf("iPhone")||-1<r.indexOf("Mac"),iPad:-1<r.indexOf("iPad"),webApp:-1==r.indexOf("Safari"),weixin:-1==r.indexOf("MicroMessenger")})};t.exports=e},function(t,n,r){"use strict";var e,i=r(87),l=(e=i)&&e.__esModule?e:{default:e},h=function(){function n(t,n,r){return n||r?String.fromCharCode(n||r):o[t]||t}function r(t){return s[t]}var e=/&quot;|&lt;|&gt;|&amp;|&nbsp;|&apos;|&#(\d+);|&#(\d+)/g,i=/['<> "&]/g,o={"&quot;":'"',"&lt;":"<","&gt;":">","&amp;":"&","&nbsp;":" "},u=/\u00a0/g,c=/<br\s*\/?>/gi,f=/\r?\n/g,a=/\s/g,s={};for(var t in o)s[o[t]]=t;return o["&apos;"]="'",s["'"]="&#39;",{encode:function(t){return t?(""+t).replace(i,r).replace(f,"<br/>").replace(a,"&nbsp;"):""},decode:function(t){return t?(""+t).replace(c,"\n").replace(e,n).replace(u," "):""},encodeBase16:function(t){if(!t)return t;for(var n=[],r=0,e=(t+="").length;r<e;r++)n.push(t.charCodeAt(r).toString(16).toUpperCase());return n.join("")},encodeBase16forJSON:function(t){if(!t)return t;for(var n=[],r=0,e=(t=t.replace(/[\u4E00-\u9FBF]/gi,function(t){return escape(t).replace("%u","\\u")})).length;r<e;r++)n.push(t.charCodeAt(r).toString(16).toUpperCase());return n.join("")},decodeBase16:function(t){if(!t)return t;for(var n=[],r=0,e=(t+="").length;r<e;r+=2)n.push(String.fromCharCode("0x"+t.slice(r,r+2)));return n.join("")},encodeObject:function(t){if(t instanceof Array)for(var n=0,r=t.length;n<r;n++)t[n]=h.encodeObject(t[n]);else if("object"==(void 0===t?"undefined":(0,l.default)(t)))for(var e in t)t[e]=h.encodeObject(t[e]);else if("string"==typeof t)return h.encode(t);return t},loadScript:function(t){var n=document.createElement("script");document.getElementsByTagName("body")[0].appendChild(n),n.setAttribute("src",t)},addLoadEvent:function(t){var n=window.onload;"function"!=typeof window.onload?window.onload=t:window.onload=function(){n(),t()}}}}();t.exports=h},function(t,n,r){"use strict";var e=r(131)(!0);t.exports=function(t,n,r){return n+(r?e(t,n).length:1)}},function(t,n,r){"use strict";var c=r(17),f=r(78),a=r(8);t.exports=function(t){for(var n=c(this),r=a(n.length),e=arguments.length,i=f(1<e?arguments[1]:void 0,r),o=2<e?arguments[2]:void 0,u=void 0===o?r:f(o,r);i<u;)n[i++]=t;return n}},function(t,n,r){var e=r(215);t.exports=function(t,n){return new(e(t))(n)}},function(t,n,r){"use strict";var e=r(11),i=r(75);t.exports=function(t,n,r){n in t?e.f(t,n,i(0,r)):t[n]=r}},function(t,n,r){var e=r(5),i=r(3).document,o=e(i)&&e(i.createElement);t.exports=function(t){return o?i.createElement(t):{}}},function(t,n){t.exports="constructor,hasOwnProperty,isPrototypeOf,propertyIsEnumerable,toLocaleString,toString,valueOf".split(",")},function(t,n,r){var e=r(7)("match");t.exports=function(n){var r=/./;try{"/./"[n](r)}catch(t){try{return r[e]=!1,!"/./"[n](r)}catch(n){}}return!0}},function(t,n,r){var e=r(3).document;t.exports=e&&e.documentElement},function(t,n,r){var o=r(5),u=r(153).set;t.exports=function(t,n,r){var e,i=n.constructor;return i!==r&&"function"==typeof i&&(e=i.prototype)!==r.prototype&&o(e)&&u&&u(t,e),t}},function(t,n,r){var e=r(82),i=r(7)("iterator"),o=Array.prototype;t.exports=function(t){return void 0!==t&&(e.Array===t||o[i]===t)}},function(t,n,r){"use strict";var e=r(72),i=r(75),o=r(83),u={};r(26)(u,r(7)("iterator"),function(){return this}),t.exports=function(t,n,r){t.prototype=e(u,{next:i(1,r)}),o(t,n+" Iterator")}},function(t,n,r){"use strict";var x=r(68),m=r(1),S=r(27),w=r(26),_=r(82),O=r(146),E=r(83),M=r(32),P=r(7)("iterator"),j=!([].keys&&"next"in[].keys()),F="values",A=function(){return this};t.exports=function(t,n,r,e,i,o,u){O(r,n,e);var c,f,a,s=function(t){if(!j&&t in p)return p[t];switch(t){case"keys":case F:return function(){return new r(this,t)}}return function(){return new r(this,t)}},l=n+" Iterator",h=i==F,v=!1,p=t.prototype,d=p[P]||p["@@iterator"]||i&&p[i],y=d||s(i),g=i?h?s("entries"):y:void 0,b="Array"==n&&p.entries||d;if(b&&((a=M(b.call(new t)))!==Object.prototype&&a.next&&(E(a,l,!0),x||"function"==typeof a[P]||w(a,P,A))),h&&d&&d.name!==F&&(v=!0,y=function(){return d.call(this)}),x&&!u||!j&&!v&&p[P]||w(p,P,y),_[n]=y,_[l]=A,i)if(c={values:h?y:s(F),keys:o?y:s("keys"),entries:g},u)for(f in c)f in p||S(p,f,c[f]);else m(m.P+m.F*(j||v),n,c);return c}},function(t,n){var r=Math.expm1;t.exports=!r||22025.465794806718<r(10)||r(10)<22025.465794806718||-2e-17!=r(-2e-17)?function(t){return 0==(t=+t)?t:-1e-6<t&&t<1e-6?t+t*t/2:Math.exp(t)-1}:r},function(t,n){t.exports=Math.sign||function(t){return 0==(t=+t)||t!=t?t:t<0?-1:1}},function(t,n,r){var c=r(3),f=r(158).set,a=c.MutationObserver||c.WebKitMutationObserver,s=c.process,l=c.Promise,h="process"==r(45)(s);t.exports=function(){var r,e,i,t=function(){var t,n;for(h&&(t=s.domain)&&t.exit();r;){n=r.fn,r=r.next;try{n()}catch(t){throw r?i():e=void 0,t}}e=void 0,t&&t.enter()};if(h)i=function(){s.nextTick(t)};else if(!a||c.navigator&&c.navigator.standalone)if(l&&l.resolve){var n=l.resolve(void 0);i=function(){n.then(t)}}else i=function(){f.call(c,t)};else{var o=!0,u=document.createTextNode("");new a(t).observe(u,{characterData:!0}),i=function(){u.data=o=!o}}return function(t){var n={fn:t,next:void 0};e&&(e.next=n),r||(r=n,i()),e=n}}},function(t,n,r){"use strict";function e(t){var r,e;this.promise=new t(function(t,n){if(void 0!==r||void 0!==e)throw TypeError("Bad Promise constructor");r=t,e=n}),this.resolve=i(r),this.reject=i(e)}var i=r(21);t.exports.f=function(t){return new e(t)}},function(t,n,r){"use strict";var e,i,u=r(115),c=RegExp.prototype.exec,f=String.prototype.replace,o=c,a="lastIndex",s=(e=/a/,i=/b*/g,c.call(e,"a"),c.call(i,"a"),0!==e[a]||0!==i[a]),l=void 0!==/()??/.exec("")[1];(s||l)&&(o=function(t){var n,r,e,i,o=this;return l&&(r=new RegExp("^"+o.source+"$(?!\\s)",u.call(o))),s&&(n=o[a]),e=c.call(o,t),s&&e&&(o[a]=o.global?e.index+e[0].length:n),l&&e&&1<e.length&&f.call(e[0],r,function(){for(i=1;i<arguments.length-2;i++)void 0===arguments[i]&&(e[i]=void 0)}),e}),t.exports=o},function(t,n,i){var r=i(5),e=i(2),o=function(t,n){if(e(t),!r(n)&&null!==n)throw TypeError(n+": can't set as prototype!")};t.exports={set:Object.setPrototypeOf||("__proto__"in{}?function(t,r,e){try{(e=i(47)(Function.call,i(31).f(Object.prototype,"__proto__").set,2))(t,[]),r=!(t instanceof Array)}catch(t){r=!0}return function(t,n){return o(t,n),r?t.__proto__=n:e(t,n),t}}({},!1):void 0),check:o}},function(t,n,r){var e=r(118)("keys"),i=r(79);t.exports=function(t){return e[t]||(e[t]=i(t))}},function(t,n,r){var e=r(124),i=r(51);t.exports=function(t,n,r){if(e(n))throw TypeError("String#"+r+" doesn't accept regex!");return String(i(t))}},function(t,n,r){"use strict";var i=r(49),o=r(51);t.exports=function(t){var n=String(o(this)),r="",e=i(t);if(e<0||e==1/0)throw RangeError("Count can't be negative");for(;0<e;(e>>>=1)&&(n+=n))1&e&&(r+=n);return r}},function(t,n){t.exports="\t\n\v\f\r   ᠎             　\u2028\u2029\ufeff"},function(t,n,r){var e,i,o,u=r(47),c=r(175),f=r(143),a=r(140),s=r(3),l=s.process,h=s.setImmediate,v=s.clearImmediate,p=s.MessageChannel,d=s.Dispatch,y=0,g={},b="onreadystatechange",x=function(){var t=+this;if(g.hasOwnProperty(t)){var n=g[t];delete g[t],n()}},m=function(t){x.call(t.data)};h&&v||(h=function(t){for(var n=[],r=1;arguments.length>r;)n.push(arguments[r++]);return g[++y]=function(){c("function"==typeof t?t:Function(t),n)},e(y),y},v=function(t){delete g[t]},"process"==r(45)(l)?e=function(t){l.nextTick(u(x,t,1))}:d&&d.now?e=function(t){d.now(u(x,t,1))}:p?(o=(i=new p).port2,i.port1.onmessage=m,e=u(o.postMessage,o,1)):s.addEventListener&&"function"==typeof postMessage&&!s.importScripts?(e=function(t){s.postMessage(t+"","*")},s.addEventListener("message",m,!1)):e=b in a("script")?function(t){f.appendChild(a("script"))[b]=function(){f.removeChild(this),x.call(t)}}:function(t){setTimeout(u(x,t,1),0)}),t.exports={set:h,clear:v}},function(t,n,r){"use strict";function e(t,n,r){var e,i,o,u=new Array(r),c=8*r-n-1,f=(1<<c)-1,a=f>>1,s=23===n?W(2,-24)-W(2,-77):0,l=0,h=t<0||0===t&&1/t<0?1:0;for((t=G(t))!=t||t===C?(i=t!=t?1:0,e=f):(e=U(V(t)/B),t*(o=W(2,-e))<1&&(e--,o*=2),2<=(t+=1<=e+a?s/o:s*W(2,1-a))*o&&(e++,o/=2),f<=e+a?(i=0,e=f):1<=e+a?(i=(t*o-1)*W(2,n),e+=a):(i=t*W(2,a-1)*W(2,n),e=0));8<=n;u[l++]=255&i,i/=256,n-=8);for(e=e<<n|i,c+=n;0<c;u[l++]=255&e,e/=256,c-=8);return u[--l]|=128*h,u}function i(t,n,r){var e,i=8*r-n-1,o=(1<<i)-1,u=o>>1,c=i-7,f=r-1,a=t[f--],s=127&a;for(a>>=7;0<c;s=256*s+t[f],f--,c-=8);for(e=s&(1<<-c)-1,s>>=-c,c+=n;0<c;e=256*e+t[f],f--,c-=8);if(0===s)s=1-u;else{if(s===o)return e?NaN:a?-C:C;e+=W(2,n),s-=u}return(a?-1:1)*e*W(2,s-n)}function o(t){return t[3]<<24|t[2]<<16|t[1]<<8|t[0]}function u(t){return[255&t]}function c(t){return[255&t,t>>8&255]}function f(t){return[255&t,t>>8&255,t>>16&255,t>>24&255]}function a(t){return e(t,52,8)}function s(t){return e(t,23,4)}function l(t,n,r){M(t[I],n,{get:function(){return this[r]}})}function h(t,n,r,e){var i=O(+r);if(i+n>t[H])throw R(L);var o=t[K]._b,u=i+t[J],c=o.slice(u,u+n);return e?c:c.reverse()}function v(t,n,r,e,i,o){var u=O(+r);if(u+n>t[H])throw R(L);for(var c=t[K]._b,f=u+t[J],a=e(+i),s=0;s<n;s++)c[f+s]=a[o?s:n-s-1]}var p=r(3),d=r(10),y=r(68),g=r(132),b=r(26),x=r(76),m=r(4),S=r(70),w=r(49),_=r(8),O=r(194),E=r(73).f,M=r(11).f,P=r(137),j=r(83),F="ArrayBuffer",A="DataView",I="prototype",L="Wrong index!",N=p[F],T=p[A],k=p.Math,R=p.RangeError,C=p.Infinity,D=N,G=k.abs,W=k.pow,U=k.floor,V=k.log,B=k.LN2,q="byteLength",z="byteOffset",K=d?"_b":"buffer",H=d?"_l":q,J=d?"_o":z;if(g.ABV){if(!m(function(){N(1)})||!m(function(){new N(-1)})||m(function(){return new N,new N(1.5),new N(NaN),N.name!=F})){for(var $,Y=(N=function(t){return S(this,N),new D(O(t))})[I]=D[I],X=E(D),Q=0;X.length>Q;)($=X[Q++])in N||b(N,$,D[$]);y||(Y.constructor=N)}var Z=new T(new N(2)),tt=T[I].setInt8;Z.setInt8(0,2147483648),Z.setInt8(1,2147483649),!Z.getInt8(0)&&Z.getInt8(1)||x(T[I],{setInt8:function(t,n){tt.call(this,t,n<<24>>24)},setUint8:function(t,n){tt.call(this,t,n<<24>>24)}},!0)}else N=function(t){S(this,N,F);var n=O(t);this._b=P.call(new Array(n),0),this[H]=n},T=function(t,n,r){S(this,T,A),S(t,N,A);var e=t[H],i=w(n);if(i<0||e<i)throw R("Wrong offset!");if(e<i+(r=void 0===r?e-i:_(r)))throw R("Wrong length!");this[K]=t,this[J]=i,this[H]=r},d&&(l(N,q,"_l"),l(T,"buffer","_b"),l(T,q,"_l"),l(T,z,"_o")),x(T[I],{getInt8:function(t){return h(this,1,t)[0]<<24>>24},getUint8:function(t){return h(this,1,t)[0]},getInt16:function(t){var n=h(this,2,t,arguments[1]);return(n[1]<<8|n[0])<<16>>16},getUint16:function(t){var n=h(this,2,t,arguments[1]);return n[1]<<8|n[0]},getInt32:function(t){return o(h(this,4,t,arguments[1]))},getUint32:function(t){return o(h(this,4,t,arguments[1]))>>>0},getFloat32:function(t){return i(h(this,4,t,arguments[1]),23,4)},getFloat64:function(t){return i(h(this,8,t,arguments[1]),52,8)},setInt8:function(t,n){v(this,1,t,u,n)},setUint8:function(t,n){v(this,1,t,u,n)},setInt16:function(t,n){v(this,2,t,c,n,arguments[2])},setUint16:function(t,n){v(this,2,t,c,n,arguments[2])},setInt32:function(t,n){v(this,4,t,f,n,arguments[2])},setUint32:function(t,n){v(this,4,t,f,n,arguments[2])},setFloat32:function(t,n){v(this,4,t,s,n,arguments[2])},setFloat64:function(t,n){v(this,8,t,a,n,arguments[2])}});j(N,F),j(T,A),b(T[I],g.VIEW,!0),n[F]=N,n[A]=T},function(t,n,r){var e=r(3),i=r(46),o=r(68),u=r(195),c=r(11).f;t.exports=function(t){var n=i.Symbol||(i.Symbol=o?{}:e.Symbol||{});"_"==t.charAt(0)||t in n||c(n,t,{value:u.f(t)})}},function(t,n,r){var e=r(81),i=r(7)("iterator"),o=r(82);t.exports=r(46).getIteratorMethod=function(t){if(null!=t)return t[i]||t["@@iterator"]||o[e(t)]}},function(t,n,r){"use strict";var e=r(67),i=r(178),o=r(82),u=r(33);t.exports=r(147)(Array,"Array",function(t,n){this._t=u(t),this._i=0,this._k=n},function(){var t=this._t,n=this._k,r=this._i++;return!t||r>=t.length?(this._t=void 0,i(1)):i(0,"keys"==n?r:"values"==n?t[r]:[r,t[r]])},"values"),o.Arguments=o.Array,e("keys"),e("values"),e("entries")},function(t,n){t.exports=function(t,n){t.classList?t.classList.add(n):t.className+=" "+n}},function(t,n){t.exports=function(t,n){if(t.classList)t.classList.remove(n);else{var r=new RegExp("(^|\\b)"+n.split(" ").join("|")+"(\\b|$)","gi");t.className=t.className.replace(r," ")}}},function(t,n,r){var e=r(45);t.exports=function(t,n){if("number"!=typeof t&&"Number"!=e(t))throw TypeError(n);return+t}},function(t,n,r){"use strict";var a=r(17),s=r(78),l=r(8);t.exports=[].copyWithin||function(t,n){var r=a(this),e=l(r.length),i=s(t,e),o=s(n,e),u=2<arguments.length?arguments[2]:void 0,c=Math.min((void 0===u?e:s(u,e))-o,e-i),f=1;for(o<i&&i<o+c&&(f=-1,o+=c-1,i+=c-1);0<c--;)o in r?r[i]=r[o]:delete r[i],i+=f,o+=f;return r}},function(t,n,r){var e=r(71);t.exports=function(t,n){var r=[];return e(t,!1,r.push,r,n),r}},function(t,n,r){var s=r(21),l=r(17),h=r(116),v=r(8);t.exports=function(t,n,r,e,i){s(n);var o=l(t),u=h(o),c=v(o.length),f=i?c-1:0,a=i?-1:1;if(r<2)for(;;){if(f in u){e=u[f],f+=a;break}if(f+=a,i?f<0:c<=f)throw TypeError("Reduce of empty array with no initial value")}for(;i?0<=f:f<c;f+=a)f in u&&(e=n(e,u[f],f,o));return e}},function(t,n,r){"use strict";var o=r(21),u=r(5),c=r(175),f=[].slice,a={};t.exports=Function.bind||function(n){var r=o(this),e=f.call(arguments,1),i=function(){var t=e.concat(f.call(arguments));return this instanceof i?function(t,n,r){if(!(n in a)){for(var e=[],i=0;i<n;i++)e[i]="a["+i+"]";a[n]=Function("F,a","return new F("+e.join(",")+")")}return a[n](t,r)}(r,t.length,t):c(r,t,n)};return u(r.prototype)&&(i.prototype=r.prototype),i}},function(t,n,r){"use strict";var u=r(11).f,c=r(72),f=r(76),a=r(47),s=r(70),l=r(71),e=r(147),i=r(178),o=r(77),h=r(10),v=r(69).fastKey,p=r(80),d=h?"_s":"size",y=function(t,n){var r,e=v(n);if("F"!==e)return t._i[e];for(r=t._f;r;r=r.n)if(r.k==n)return r};t.exports={getConstructor:function(t,o,r,e){var i=t(function(t,n){s(t,i,o,"_i"),t._t=o,t._i=c(null),t._f=void 0,t._l=void 0,t[d]=0,null!=n&&l(n,r,t[e],t)});return f(i.prototype,{clear:function(){for(var t=p(this,o),n=t._i,r=t._f;r;r=r.n)r.r=!0,r.p&&(r.p=r.p.n=void 0),delete n[r.i];t._f=t._l=void 0,t[d]=0},delete:function(t){var n=p(this,o),r=y(n,t);if(r){var e=r.n,i=r.p;delete n._i[r.i],r.r=!0,i&&(i.n=e),e&&(e.p=i),n._f==r&&(n._f=e),n._l==r&&(n._l=i),n[d]--}return!!r},forEach:function(t){p(this,o);for(var n,r=a(t,1<arguments.length?arguments[1]:void 0,3);n=n?n.n:this._f;)for(r(n.v,n.k,this);n&&n.r;)n=n.p},has:function(t){return!!y(p(this,o),t)}}),h&&u(i.prototype,"size",{get:function(){return p(this,o)[d]}}),i},def:function(t,n,r){var e,i,o=y(t,n);return o?o.v=r:(t._l=o={i:i=v(n,!0),k:n,v:r,p:e=t._l,n:void 0,r:!1},t._f||(t._f=o),e&&(e.n=o),t[d]++,"F"!==i&&(t._i[i]=o)),t},getEntry:y,setStrong:function(t,r,n){e(t,r,function(t,n){this._t=p(t,r),this._k=n,this._l=void 0},function(){for(var t=this,n=t._k,r=t._l;r&&r.r;)r=r.p;return t._t&&(t._l=r=r?r.n:t._t._f)?i(0,"keys"==n?r.k:"values"==n?r.v:[r.k,r.v]):(t._t=void 0,i(1))},n?"entries":"values",!n,!0),o(r)}}},function(t,n,r){var e=r(81),i=r(167);t.exports=function(t){return function(){if(e(this)!=t)throw TypeError(t+"#toJSON isn't generic");return i(this)}}},function(t,n,r){"use strict";var u=r(76),c=r(69).getWeak,i=r(2),f=r(5),a=r(70),s=r(71),e=r(50),l=r(30),h=r(80),o=e(5),v=e(6),p=0,d=function(t){return t._l||(t._l=new y)},y=function(){this.a=[]},g=function(t,n){return o(t.a,function(t){return t[0]===n})};y.prototype={get:function(t){var n=g(this,t);if(n)return n[1]},has:function(t){return!!g(this,t)},set:function(t,n){var r=g(this,t);r?r[1]=n:this.a.push([t,n])},delete:function(n){var t=v(this.a,function(t){return t[0]===n});return~t&&this.a.splice(t,1),!!~t}},t.exports={getConstructor:function(t,r,e,i){var o=t(function(t,n){a(t,o,r,"_i"),t._t=r,t._i=p++,t._l=void 0,null!=n&&s(n,e,t[i],t)});return u(o.prototype,{delete:function(t){if(!f(t))return!1;var n=c(t);return!0===n?d(h(this,r)).delete(t):n&&l(n,this._i)&&delete n[this._i]},has:function(t){if(!f(t))return!1;var n=c(t);return!0===n?d(h(this,r)).has(t):n&&l(n,this._i)}}),o},def:function(t,n,r){var e=c(i(n),!0);return!0===e?d(t).set(n,r):e[t._i]=r,t},ufstore:d}},function(t,n,r){"use strict";var p=r(123),d=r(5),y=r(8),g=r(47),b=r(7)("isConcatSpreadable");t.exports=function t(n,r,e,i,o,u,c,f){for(var a,s,l=o,h=0,v=!!c&&g(c,f,3);h<i;){if(h in e){if(a=v?v(e[h],h,r):e[h],s=!1,d(a)&&(s=void 0!==(s=a[b])?!!s:p(a)),s&&0<u)l=t(n,r,a,y(a.length),l,u-1)-1;else{if(9007199254740991<=l)throw TypeError();n[l]=a}l++}h++}return l}},function(t,n,r){t.exports=!r(10)&&!r(4)(function(){return 7!=Object.defineProperty(r(140)("div"),"a",{get:function(){return 7}}).a})},function(t,n){t.exports=function(t,n,r){var e=void 0===r;switch(n.length){case 0:return e?t():t.call(r);case 1:return e?t(n[0]):t.call(r,n[0]);case 2:return e?t(n[0],n[1]):t.call(r,n[0],n[1]);case 3:return e?t(n[0],n[1],n[2]):t.call(r,n[0],n[1],n[2]);case 4:return e?t(n[0],n[1],n[2],n[3]):t.call(r,n[0],n[1],n[2],n[3])}return t.apply(r,n)}},function(t,n,r){var e=r(5),i=Math.floor;t.exports=function(t){return!e(t)&&isFinite(t)&&i(t)===t}},function(t,n,r){var o=r(2);t.exports=function(t,n,r,e){try{return e?n(o(r)[0],r[1]):n(r)}catch(n){var i=t.return;throw void 0!==i&&o(i.call(t)),n}}},function(t,n){t.exports=function(t,n){return{value:n,done:!!t}}},function(t,n,r){var o=r(149),e=Math.pow,u=e(2,-52),c=e(2,-23),f=e(2,127)*(2-c),a=e(2,-126);t.exports=Math.fround||function(t){var n,r,e=Math.abs(t),i=o(t);return e<a?i*(e/a/c+1/u-1/u)*a*c:f<(r=(n=(1+c/u)*e)-(n-e))||r!=r?i*(1/0):i*r}},function(t,n){t.exports=Math.log1p||function(t){return-1e-8<(t=+t)&&t<1e-8?t-t*t/2:Math.log(1+t)}},function(t,n){t.exports=Math.scale||function(t,n,r,e,i){return 0===arguments.length||t!=t||n!=n||r!=r||e!=e||i!=i?NaN:t===1/0||t===-1/0?t:(t-n)*(i-e)/(r-n)+e}},function(t,n,r){"use strict";var h=r(10),v=r(74),p=r(127),d=r(117),y=r(17),g=r(116),i=Object.assign;t.exports=!i||r(4)(function(){var t={},n={},r=Symbol(),e="abcdefghijklmnopqrst";return t[r]=7,e.split("").forEach(function(t){n[t]=t}),7!=i({},t)[r]||Object.keys(i({},n)).join("")!=e})?function(t,n){for(var r=y(t),e=arguments.length,i=1,o=p.f,u=d.f;i<e;)for(var c,f=g(arguments[i++]),a=o?v(f).concat(o(f)):v(f),s=a.length,l=0;l<s;)c=a[l++],h&&!u.call(f,c)||(r[c]=f[c]);return r}:i},function(t,n,r){var u=r(11),c=r(2),f=r(74);t.exports=r(10)?Object.defineProperties:function(t,n){c(t);for(var r,e=f(n),i=e.length,o=0;o<i;)u.f(t,r=e[o++],n[r]);return t}},function(t,n,r){var e=r(33),i=r(73).f,o={}.toString,u="object"==typeof window&&window&&Object.getOwnPropertyNames?Object.getOwnPropertyNames(window):[];t.exports.f=function(t){return u&&"[object Window]"==o.call(t)?function(t){try{return i(t)}catch(t){return u.slice()}}(t):i(e(t))}},function(t,n,r){var u=r(30),c=r(33),f=r(120)(!1),a=r(154)("IE_PROTO");t.exports=function(t,n){var r,e=c(t),i=0,o=[];for(r in e)r!=a&&u(e,r)&&o.push(r);for(;n.length>i;)u(e,r=n[i++])&&(~f(o,r)||o.push(r));return o}},function(t,n,r){var f=r(10),a=r(74),s=r(33),l=r(117).f;t.exports=function(c){return function(t){for(var n,r=s(t),e=a(r),i=e.length,o=0,u=[];o<i;)n=e[o++],f&&!l.call(r,n)||u.push(c?[n,r[n]]:r[n]);return u}}},function(t,n,r){var e=r(73),i=r(127),o=r(2),u=r(3).Reflect;t.exports=u&&u.ownKeys||function(t){var n=e.f(o(t)),r=i.f;return r?n.concat(r(t)):n}},function(t,n,r){var e=r(3).parseFloat,i=r(84).trim;t.exports=1/e(r(157)+"-0")!=-1/0?function(t){var n=i(String(t),3),r=e(n);return 0===r&&"-"==n.charAt(0)?-0:r}:e},function(t,n,r){var e=r(3).parseInt,i=r(84).trim,o=r(157),u=/^[-+]?0[xX]/;t.exports=8!==e(o+"08")||22!==e(o+"0x16")?function(t,n){var r=i(String(t),3);return e(r,n>>>0||(u.test(r)?16:10))}:e},function(t,n){t.exports=function(t){try{return{e:!1,v:t()}}catch(t){return{e:!0,v:t}}}},function(t,n,r){var e=r(2),i=r(5),o=r(151);t.exports=function(t,n){if(e(t),i(n)&&n.constructor===t)return n;var r=o.f(t);return(0,r.resolve)(n),r.promise}},function(t,n){t.exports=Object.is||function(t,n){return t===n?0!==t||1/t==1/n:t!=t&&n!=n}},function(t,n,r){var s=r(8),l=r(156),h=r(51);t.exports=function(t,n,r,e){var i=String(h(t)),o=i.length,u=void 0===r?" ":String(r),c=s(n);if(c<=o||""==u)return i;var f=c-o,a=l.call(u,Math.ceil(f/u.length));return a.length>f&&(a=a.slice(0,f)),e?a+i:i+a}},function(t,n,r){var e=r(49),i=r(8);t.exports=function(t){if(void 0===t)return 0;var n=e(t),r=i(n);if(n!==r)throw RangeError("Wrong length!");return r}},function(t,n,r){n.f=r(7)},function(t,n,r){"use strict";var e=r(170),i=r(80);t.exports=r(121)("Map",function(t){return function(){return t(this,0<arguments.length?arguments[0]:void 0)}},{get:function(t){var n=e.getEntry(i(this,"Map"),t);return n&&n.v},set:function(t,n){return e.def(i(this,"Map"),0===t?0:t,n)}},e,!0)},function(t,n,r){"use strict";var e=r(152);r(1)({target:"RegExp",proto:!0,forced:e!==/./.exec},{exec:e})},function(t,n,r){r(10)&&"g"!=/./g.flags&&r(11).f(RegExp.prototype,"flags",{configurable:!0,get:r(115)})},function(t,n,r){"use strict";var e=r(170),i=r(80);t.exports=r(121)("Set",function(t){return function(){return t(this,0<arguments.length?arguments[0]:void 0)}},{add:function(t){return e.def(i(this,"Set"),t=0===t?0:t,t)}},e)},function(t,n,r){"use strict";var o,e=r(3),i=r(50)(0),u=r(27),c=r(69),f=r(182),a=r(172),s=r(5),l=r(80),h=r(80),v=!e.ActiveXObject&&"ActiveXObject"in e,p="WeakMap",d=c.getWeak,y=Object.isExtensible,g=a.ufstore,b=function(t){return function(){return t(this,0<arguments.length?arguments[0]:void 0)}},x={get:function(t){if(s(t)){var n=d(t);return!0===n?g(l(this,p)).get(t):n?n[this._i]:void 0}},set:function(t,n){return a.def(l(this,p),t,n)}},m=t.exports=r(121)(p,b,x,a,!0,!0);h&&v&&(f((o=a.getConstructor(b,p)).prototype,x),c.NEED=!0,i(["delete","has","get","set"],function(e){var t=m.prototype,i=t[e];u(t,e,function(t,n){if(!s(t)||y(t))return i.call(this,t,n);this._f||(this._f=new o);var r=this._f[e](t,n);return"set"==e?this:r})}))},,,,function(t,n){"use strict";t.exports={init:function(){var t=document.querySelector("#page-nav");t&&!document.querySelector("#page-nav .extend.prev")&&(t.innerHTML='<a class="extend prev disabled" rel="prev">&laquo; Prev</a>'+t.innerHTML),t&&!document.querySelector("#page-nav .extend.next")&&(t.innerHTML=t.innerHTML+'<a class="extend next disabled" rel="next">Next &raquo;</a>'),yiliaConfig&&yiliaConfig.open_in_new&&document.querySelectorAll(".article-entry a:not(.article-more-a)").forEach(function(t){var n=t.getAttribute("target");n&&""!==n||t.setAttribute("target","_blank")}),yiliaConfig&&yiliaConfig.toc_hide_index&&document.querySelectorAll(".toc-number").forEach(function(t){t.style.display="none"})}}},function(t,n,r){"use strict";function e(t){return t&&t.__esModule?t:{default:t}}function i(t,n,r,e,i){var o=function(t){for(var n=t.offsetLeft,r=t.offsetParent;null!==r;)n+=r.offsetLeft,r=r.offsetParent;return n}(t),u=function(t){for(var n=t.offsetTop,r=t.offsetParent;null!==r;)n+=r.offsetTop,r=r.offsetParent;return n}(t)-n;if(u-r<=i){var c=t.$newDom;c||(c=t.cloneNode(!0),(0,a.default)(t,c),(t.$newDom=c).style.position="fixed",c.style.top=(r||u)+"px",c.style.left=o+"px",c.style.zIndex=e||2,c.style.width="100%",c.style.color="#fff"),c.style.visibility="visible",t.style.visibility="hidden"}else{t.style.visibility="visible";var f=t.$newDom;f&&(f.style.visibility="hidden")}}function o(){var t=document.querySelector(".js-overlay"),n=document.querySelector(".js-header-menu");i(t,document.body.scrollTop,-63,2,0),i(n,document.body.scrollTop,1,3,0)}var f=e(r(163)),a=e((e(r(164)),r(414))),u=e(r(134)),c=e(r(204)),s=r(135);u.default.versions.mobile&&window.screen.width<800&&(function(){for(var t=document.querySelectorAll(".js-header-menu li a"),n=window.location.pathname,r=0,e=t.length;r<e;r++){var i=t[r];o=n,u=i.getAttribute("href"),c=/\/|index.html/g,o.replace(c,"")===u.replace(c,"")&&(0,f.default)(i,"active")}var o,u,c}(),document.querySelector("#container").addEventListener("scroll",function(t){o()}),window.addEventListener("scroll",function(t){o()}),o()),(0,s.addLoadEvent)(function(){c.default.init()}),t.exports={}},,,function(t,n,r){(function(t){"use strict";function n(t,n,r){t[n]||Object.defineProperty(t,n,{writable:!0,configurable:!0,value:r})}if(r(413),r(209),r(211),t._babelPolyfill)throw new Error("only one instance of babel-polyfill is allowed");t._babelPolyfill=!0;n(String.prototype,"padLeft","".padStart),n(String.prototype,"padRight","".padEnd),"pop,reverse,shift,keys,values,entries,indexOf,every,some,forEach,map,filter,find,findIndex,includes,join,slice,concat,push,splice,unshift,sort,lastIndexOf,reduce,reduceRight,copyWithin,fill".split(",").forEach(function(t){[][t]&&n(Array,t,Function.call.bind([][t]))})}).call(n,function(){return this}())},function(L,t){(function(t){!function(t){"use strict";function o(t,n,r,e){var o,u,c,f,i=n&&n.prototype instanceof h?n:h,a=Object.create(i.prototype),s=new p(e||[]);return a._invoke=(o=t,u=r,c=s,f=_,function(t,n){if(f===E)throw new Error("Generator is already running");if(f===M){if("throw"===t)throw n;return d()}for(c.method=t,c.arg=n;;){var r=c.delegate;if(r){var e=v(r,c);if(e){if(e===P)continue;return e}}if("next"===c.method)c.sent=c._sent=c.arg;else if("throw"===c.method){if(f===_)throw f=M,c.arg;c.dispatchException(c.arg)}else"return"===c.method&&c.abrupt("return",c.arg);f=E;var i=l(o,u,c);if("normal"===i.type){if(f=c.done?M:O,i.arg===P)continue;return{value:i.arg,done:c.done}}"throw"===i.type&&(f=M,c.method="throw",c.arg=i.arg)}}),a}function l(t,n,r){try{return{type:"normal",arg:t.call(n,r)}}catch(t){return{type:"throw",arg:t}}}function h(){}function r(){}function n(){}function e(t){["next","throw","return"].forEach(function(n){t[n]=function(t){return this._invoke(n,t)}})}function u(c){function f(t,n,r,e){var i=l(c[t],c,n);if("throw"!==i.type){var o=i.arg,u=o.value;return u&&"object"==typeof u&&y.call(u,"__await")?Promise.resolve(u.__await).then(function(t){f("next",t,r,e)},function(t){f("throw",t,r,e)}):Promise.resolve(u).then(function(t){o.value=t,r(o)},e)}e(i.arg)}var n;"object"==typeof t.process&&t.process.domain&&(f=t.process.domain.bind(f)),this._invoke=function(r,e){function t(){return new Promise(function(t,n){f(r,e,t,n)})}return n=n?n.then(t,t):t()}}function v(t,n){var r=t.iterator[n.method];if(r===a){if(n.delegate=null,"throw"===n.method){if(t.iterator.return&&(n.method="return",n.arg=a,v(t,n),"throw"===n.method))return P;n.method="throw",n.arg=new TypeError("The iterator does not provide a 'throw' method")}return P}var e=l(r,t.iterator,n.arg);if("throw"===e.type)return n.method="throw",n.arg=e.arg,n.delegate=null,P;var i=e.arg;return i?i.done?(n[t.resultName]=i.value,n.next=t.nextLoc,"return"!==n.method&&(n.method="next",n.arg=a),n.delegate=null,P):i:(n.method="throw",n.arg=new TypeError("iterator result is not an object"),n.delegate=null,P)}function i(t){var n={tryLoc:t[0]};1 in t&&(n.catchLoc=t[1]),2 in t&&(n.finallyLoc=t[2],n.afterLoc=t[3]),this.tryEntries.push(n)}function c(t){var n=t.completion||{};n.type="normal",delete n.arg,t.completion=n}function p(t){this.tryEntries=[{tryLoc:"root"}],t.forEach(i,this),this.reset(!0)}function f(n){if(n){var t=n[b];if(t)return t.call(n);if("function"==typeof n.next)return n;if(!isNaN(n.length)){var r=-1,e=function t(){for(;++r<n.length;)if(y.call(n,r))return t.value=n[r],t.done=!1,t;return t.value=a,t.done=!0,t};return e.next=e}}return{next:d}}function d(){return{value:a,done:!0}}var a,s=Object.prototype,y=s.hasOwnProperty,g="function"==typeof Symbol?Symbol:{},b=g.iterator||"@@iterator",x=g.asyncIterator||"@@asyncIterator",m=g.toStringTag||"@@toStringTag",S="object"==typeof L,w=t.regeneratorRuntime;if(w)S&&(L.exports=w);else{(w=t.regeneratorRuntime=S?L.exports:{}).wrap=o;var _="suspendedStart",O="suspendedYield",E="executing",M="completed",P={},j={};j[b]=function(){return this};var F=Object.getPrototypeOf,A=F&&F(F(f([])));A&&A!==s&&y.call(A,b)&&(j=A);var I=n.prototype=h.prototype=Object.create(j);r.prototype=I.constructor=n,n.constructor=r,n[m]=r.displayName="GeneratorFunction",w.isGeneratorFunction=function(t){var n="function"==typeof t&&t.constructor;return!!n&&(n===r||"GeneratorFunction"===(n.displayName||n.name))},w.mark=function(t){return Object.setPrototypeOf?Object.setPrototypeOf(t,n):(t.__proto__=n,m in t||(t[m]="GeneratorFunction")),t.prototype=Object.create(I),t},w.awrap=function(t){return{__await:t}},e(u.prototype),u.prototype[x]=function(){return this},w.AsyncIterator=u,w.async=function(t,n,r,e){var i=new u(o(t,n,r,e));return w.isGeneratorFunction(n)?i:i.next().then(function(t){return t.done?t.value:i.next()})},e(I),I[m]="Generator",I[b]=function(){return this},I.toString=function(){return"[object Generator]"},w.keys=function(r){var e=[];for(var t in r)e.push(t);return e.reverse(),function t(){for(;e.length;){var n=e.pop();if(n in r)return t.value=n,t.done=!1,t}return t.done=!0,t}},w.values=f,p.prototype={constructor:p,reset:function(t){if(this.prev=0,this.next=0,this.sent=this._sent=a,this.done=!1,this.delegate=null,this.method="next",this.arg=a,this.tryEntries.forEach(c),!t)for(var n in this)"t"===n.charAt(0)&&y.call(this,n)&&!isNaN(+n.slice(1))&&(this[n]=a)},stop:function(){this.done=!0;var t=this.tryEntries[0].completion;if("throw"===t.type)throw t.arg;return this.rval},dispatchException:function(r){function t(t,n){return o.type="throw",o.arg=r,e.next=t,n&&(e.method="next",e.arg=a),!!n}if(this.done)throw r;for(var e=this,n=this.tryEntries.length-1;0<=n;--n){var i=this.tryEntries[n],o=i.completion;if("root"===i.tryLoc)return t("end");if(i.tryLoc<=this.prev){var u=y.call(i,"catchLoc"),c=y.call(i,"finallyLoc");if(u&&c){if(this.prev<i.catchLoc)return t(i.catchLoc,!0);if(this.prev<i.finallyLoc)return t(i.finallyLoc)}else if(u){if(this.prev<i.catchLoc)return t(i.catchLoc,!0)}else{if(!c)throw new Error("try statement without catch or finally");if(this.prev<i.finallyLoc)return t(i.finallyLoc)}}}},abrupt:function(t,n){for(var r=this.tryEntries.length-1;0<=r;--r){var e=this.tryEntries[r];if(e.tryLoc<=this.prev&&y.call(e,"finallyLoc")&&this.prev<e.finallyLoc){var i=e;break}}i&&("break"===t||"continue"===t)&&i.tryLoc<=n&&n<=i.finallyLoc&&(i=null);var o=i?i.completion:{};return o.type=t,o.arg=n,i?(this.method="next",this.next=i.finallyLoc,P):this.complete(o)},complete:function(t,n){if("throw"===t.type)throw t.arg;return"break"===t.type||"continue"===t.type?this.next=t.arg:"return"===t.type?(this.rval=this.arg=t.arg,this.method="return",this.next="end"):"normal"===t.type&&n&&(this.next=n),P},finish:function(t){for(var n=this.tryEntries.length-1;0<=n;--n){var r=this.tryEntries[n];if(r.finallyLoc===t)return this.complete(r.completion,r.afterLoc),c(r),P}},catch:function(t){for(var n=this.tryEntries.length-1;0<=n;--n){var r=this.tryEntries[n];if(r.tryLoc===t){var e=r.completion;if("throw"===e.type){var i=e.arg;c(r)}return i}}throw new Error("illegal catch attempt")},delegateYield:function(t,n,r){return this.delegate={iterator:f(t),resultName:n,nextLoc:r},"next"===this.method&&(this.arg=a),P}}}}("object"==typeof t?t:"object"==typeof window?window:"object"==typeof self?self:this)}).call(t,function(){return this}())},,function(t,n,r){r(221),t.exports=r(46).RegExp.escape},,,,function(t,n,r){var e=r(5),i=r(123),o=r(7)("species");t.exports=function(t){var n;return i(t)&&("function"!=typeof(n=t.constructor)||n!==Array&&!i(n.prototype)||(n=void 0),e(n)&&(null===(n=n[o])&&(n=void 0))),void 0===n?Array:n}},function(t,n,r){"use strict";var e=r(4),i=Date.prototype.getTime,o=Date.prototype.toISOString,u=function(t){return 9<t?t:"0"+t};t.exports=e(function(){return"0385-07-25T07:06:39.999Z"!=o.call(new Date(-5e13-1))})||!e(function(){o.call(new Date(NaN))})?function(){if(!isFinite(i.call(this)))throw RangeError("Invalid time value");var t=this,n=t.getUTCFullYear(),r=t.getUTCMilliseconds(),e=n<0?"-":9999<n?"+":"";return e+("00000"+Math.abs(n)).slice(e?-6:-4)+"-"+u(t.getUTCMonth()+1)+"-"+u(t.getUTCDate())+"T"+u(t.getUTCHours())+":"+u(t.getUTCMinutes())+":"+u(t.getUTCSeconds())+"."+(99<r?r:"0"+u(r))+"Z"}:o},function(t,n,r){"use strict";var e=r(2),i=r(53);t.exports=function(t){if("string"!==t&&"number"!==t&&"default"!==t)throw TypeError("Incorrect hint");return i(e(this),"number"!=t)}},function(t,n,r){var c=r(74),f=r(127),a=r(117);t.exports=function(t){var n=c(t),r=f.f;if(r)for(var e,i=r(t),o=a.f,u=0;i.length>u;)o.call(t,e=i[u++])&&n.push(e);return n}},function(t,n,r){t.exports=r(118)("native-function-to-string",Function.toString)},function(t,n){t.exports=function(n,r){var e=r===Object(r)?function(t){return r[t]}:r;return function(t){return String(t).replace(n,e)}}},function(t,n,r){var e=r(1),i=r(220)(/[\\^$*+?.()|[\]{}]/g,"\\$&");e(e.S,"RegExp",{escape:function(t){return i(t)}})},function(t,n,r){var e=r(1);e(e.P,"Array",{copyWithin:r(166)}),r(67)("copyWithin")},function(t,n,r){"use strict";var e=r(1),i=r(50)(4);e(e.P+e.F*!r(48)([].every,!0),"Array",{every:function(t){return i(this,t,arguments[1])}})},function(t,n,r){var e=r(1);e(e.P,"Array",{fill:r(137)}),r(67)("fill")},function(t,n,r){"use strict";var e=r(1),i=r(50)(2);e(e.P+e.F*!r(48)([].filter,!0),"Array",{filter:function(t){return i(this,t,arguments[1])}})},function(t,n,r){"use strict";var e=r(1),i=r(50)(6),o="findIndex",u=!0;o in[]&&Array(1)[o](function(){u=!1}),e(e.P+e.F*u,"Array",{findIndex:function(t){return i(this,t,1<arguments.length?arguments[1]:void 0)}}),r(67)(o)},function(t,n,r){"use strict";var e=r(1),i=r(50)(5),o="find",u=!0;o in[]&&Array(1)[o](function(){u=!1}),e(e.P+e.F*u,"Array",{find:function(t){return i(this,t,1<arguments.length?arguments[1]:void 0)}}),r(67)(o)},function(t,n,r){"use strict";var e=r(1),i=r(50)(0),o=r(48)([].forEach,!0);e(e.P+e.F*!o,"Array",{forEach:function(t){return i(this,t,arguments[1])}})},function(t,n,r){"use strict";var h=r(47),e=r(1),v=r(17),p=r(177),d=r(145),y=r(8),g=r(139),b=r(161);e(e.S+e.F*!r(125)(function(t){Array.from(t)}),"Array",{from:function(t){var n,r,e,i,o=v(t),u="function"==typeof this?this:Array,c=arguments.length,f=1<c?arguments[1]:void 0,a=void 0!==f,s=0,l=b(o);if(a&&(f=h(f,2<c?arguments[2]:void 0,2)),null==l||u==Array&&d(l))for(r=new u(n=y(o.length));s<n;s++)g(r,s,a?f(o[s],s):o[s]);else for(i=l.call(o),r=new u;!(e=i.next()).done;s++)g(r,s,a?p(i,f,[e.value,s],!0):e.value);return r.length=s,r}})},function(t,n,r){"use strict";var e=r(1),i=r(120)(!1),o=[].indexOf,u=!!o&&1/[1].indexOf(1,-0)<0;e(e.P+e.F*(u||!r(48)(o)),"Array",{indexOf:function(t){return u?o.apply(this,arguments)||0:i(this,t,arguments[1])}})},function(t,n,r){var e=r(1);e(e.S,"Array",{isArray:r(123)})},function(t,n,r){"use strict";var e=r(1),i=r(33),o=[].join;e(e.P+e.F*(r(116)!=Object||!r(48)(o)),"Array",{join:function(t){return o.call(i(this),void 0===t?",":t)}})},function(t,n,r){"use strict";var e=r(1),i=r(33),o=r(49),u=r(8),c=[].lastIndexOf,f=!!c&&1/[1].lastIndexOf(1,-0)<0;e(e.P+e.F*(f||!r(48)(c)),"Array",{lastIndexOf:function(t){if(f)return c.apply(this,arguments)||0;var n=i(this),r=u(n.length),e=r-1;for(1<arguments.length&&(e=Math.min(e,o(arguments[1]))),e<0&&(e=r+e);0<=e;e--)if(e in n&&n[e]===t)return e||0;return-1}})},function(t,n,r){"use strict";var e=r(1),i=r(50)(1);e(e.P+e.F*!r(48)([].map,!0),"Array",{map:function(t){return i(this,t,arguments[1])}})},function(t,n,r){"use strict";var e=r(1),i=r(139);e(e.S+e.F*r(4)(function(){function t(){}return!(Array.of.call(t)instanceof t)}),"Array",{of:function(){for(var t=0,n=arguments.length,r=new("function"==typeof this?this:Array)(n);t<n;)i(r,t,arguments[t++]);return r.length=n,r}})},function(t,n,r){"use strict";var e=r(1),i=r(168);e(e.P+e.F*!r(48)([].reduceRight,!0),"Array",{reduceRight:function(t){return i(this,t,arguments.length,arguments[1],!0)}})},function(t,n,r){"use strict";var e=r(1),i=r(168);e(e.P+e.F*!r(48)([].reduce,!0),"Array",{reduce:function(t){return i(this,t,arguments.length,arguments[1],!1)}})},function(t,n,r){"use strict";var e=r(1),i=r(143),a=r(45),s=r(78),l=r(8),h=[].slice;e(e.P+e.F*r(4)(function(){i&&h.call(i)}),"Array",{slice:function(t,n){var r=l(this.length),e=a(this);if(n=void 0===n?r:n,"Array"==e)return h.call(this,t,n);for(var i=s(t,r),o=s(n,r),u=l(o-i),c=new Array(u),f=0;f<u;f++)c[f]="String"==e?this.charAt(i+f):this[i+f];return c}})},function(t,n,r){"use strict";var e=r(1),i=r(50)(3);e(e.P+e.F*!r(48)([].some,!0),"Array",{some:function(t){return i(this,t,arguments[1])}})},function(t,n,r){"use strict";var e=r(1),i=r(21),o=r(17),u=r(4),c=[].sort,f=[1,2,3];e(e.P+e.F*(u(function(){f.sort(void 0)})||!u(function(){f.sort(null)})||!r(48)(c)),"Array",{sort:function(t){return void 0===t?c.call(o(this)):c.call(o(this),i(t))}})},function(t,n,r){r(77)("Array")},function(t,n,r){var e=r(1);e(e.S,"Date",{now:function(){return(new Date).getTime()}})},function(t,n,r){var e=r(1),i=r(216);e(e.P+e.F*(Date.prototype.toISOString!==i),"Date",{toISOString:i})},function(t,n,r){"use strict";var e=r(1),i=r(17),o=r(53);e(e.P+e.F*r(4)(function(){return null!==new Date(NaN).toJSON()||1!==Date.prototype.toJSON.call({toISOString:function(){return 1}})}),"Date",{toJSON:function(t){var n=i(this),r=o(n);return"number"!=typeof r||isFinite(r)?n.toISOString():null}})},function(t,n,r){var e=r(7)("toPrimitive"),i=Date.prototype;e in i||r(26)(i,e,r(217))},function(t,n,r){var e=Date.prototype,i="Invalid Date",o="toString",u=e[o],c=e.getTime;new Date(NaN)+""!=i&&r(27)(e,o,function(){var t=c.call(this);return t==t?u.call(this):i})},function(t,n,r){var e=r(1);e(e.P,"Function",{bind:r(169)})},function(t,n,r){"use strict";var e=r(5),i=r(32),o=r(7)("hasInstance"),u=Function.prototype;o in u||r(11).f(u,o,{value:function(t){if("function"!=typeof this||!e(t))return!1;if(!e(this.prototype))return t instanceof this;for(;t=i(t);)if(this.prototype===t)return!0;return!1}})},function(t,n,r){var e=r(11).f,i=Function.prototype,o=/^\s*function ([^ (]*)/;"name"in i||r(10)&&e(i,"name",{configurable:!0,get:function(){try{return(""+this).match(o)[1]}catch(t){return""}}})},function(t,n,r){var e=r(1),i=r(180),o=Math.sqrt,u=Math.acosh;e(e.S+e.F*!(u&&710==Math.floor(u(Number.MAX_VALUE))&&u(1/0)==1/0),"Math",{acosh:function(t){return(t=+t)<1?NaN:94906265.62425156<t?Math.log(t)+Math.LN2:i(t-1+o(t-1)*o(t+1))}})},function(t,n,r){var e=r(1),i=Math.asinh;e(e.S+e.F*!(i&&0<1/i(0)),"Math",{asinh:function t(n){return isFinite(n=+n)&&0!=n?n<0?-t(-n):Math.log(n+Math.sqrt(n*n+1)):n}})},function(t,n,r){var e=r(1),i=Math.atanh;e(e.S+e.F*!(i&&1/i(-0)<0),"Math",{atanh:function(t){return 0==(t=+t)?t:Math.log((1+t)/(1-t))/2}})},function(t,n,r){var e=r(1),i=r(149);e(e.S,"Math",{cbrt:function(t){return i(t=+t)*Math.pow(Math.abs(t),1/3)}})},function(t,n,r){var e=r(1);e(e.S,"Math",{clz32:function(t){return(t>>>=0)?31-Math.floor(Math.log(t+.5)*Math.LOG2E):32}})},function(t,n,r){var e=r(1),i=Math.exp;e(e.S,"Math",{cosh:function(t){return(i(t=+t)+i(-t))/2}})},function(t,n,r){var e=r(1),i=r(148);e(e.S+e.F*(i!=Math.expm1),"Math",{expm1:i})},function(t,n,r){var e=r(1);e(e.S,"Math",{fround:r(179)})},function(t,n,r){var e=r(1),f=Math.abs;e(e.S,"Math",{hypot:function(t,n){for(var r,e,i=0,o=0,u=arguments.length,c=0;o<u;)c<(r=f(arguments[o++]))?(i=i*(e=c/r)*e+1,c=r):0<r?i+=(e=r/c)*e:i+=r;return c===1/0?1/0:c*Math.sqrt(i)}})},function(t,n,r){var e=r(1),i=Math.imul;e(e.S+e.F*r(4)(function(){return-5!=i(4294967295,5)||2!=i.length}),"Math",{imul:function(t,n){var r=65535,e=+t,i=+n,o=r&e,u=r&i;return 0|o*u+((r&e>>>16)*u+o*(r&i>>>16)<<16>>>0)}})},function(t,n,r){var e=r(1);e(e.S,"Math",{log10:function(t){return Math.log(t)*Math.LOG10E}})},function(t,n,r){var e=r(1);e(e.S,"Math",{log1p:r(180)})},function(t,n,r){var e=r(1);e(e.S,"Math",{log2:function(t){return Math.log(t)/Math.LN2}})},function(t,n,r){var e=r(1);e(e.S,"Math",{sign:r(149)})},function(t,n,r){var e=r(1),i=r(148),o=Math.exp;e(e.S+e.F*r(4)(function(){return-2e-17!=!Math.sinh(-2e-17)}),"Math",{sinh:function(t){return Math.abs(t=+t)<1?(i(t)-i(-t))/2:(o(t-1)-o(-t-1))*(Math.E/2)}})},function(t,n,r){var e=r(1),i=r(148),o=Math.exp;e(e.S,"Math",{tanh:function(t){var n=i(t=+t),r=i(-t);return n==1/0?1:r==1/0?-1:(n-r)/(o(t)+o(-t))}})},function(t,n,r){var e=r(1);e(e.S,"Math",{trunc:function(t){return(0<t?Math.floor:Math.ceil)(t)}})},function(t,n,r){"use strict";var e=r(3),i=r(30),o=r(45),u=r(144),s=r(53),c=r(4),f=r(73).f,a=r(31).f,l=r(11).f,h=r(84).trim,v="Number",p=e[v],d=p,y=p.prototype,g=o(r(72)(y))==v,b="trim"in String.prototype,x=function(t){var n=s(t,!1);if("string"==typeof n&&2<n.length){var r,e,i,o=(n=b?n.trim():h(n,3)).charCodeAt(0);if(43===o||45===o){if(88===(r=n.charCodeAt(2))||120===r)return NaN}else if(48===o){switch(n.charCodeAt(1)){case 66:case 98:e=2,i=49;break;case 79:case 111:e=8,i=55;break;default:return+n}for(var u,c=n.slice(2),f=0,a=c.length;f<a;f++)if((u=c.charCodeAt(f))<48||i<u)return NaN;return parseInt(c,e)}}return+n};if(!p(" 0o1")||!p("0b1")||p("+0x1")){p=function(t){var n=arguments.length<1?0:t,r=this;return r instanceof p&&(g?c(function(){y.valueOf.call(r)}):o(r)!=v)?u(new d(x(n)),r,p):x(n)};for(var m,S=r(10)?f(d):"MAX_VALUE,MIN_VALUE,NaN,NEGATIVE_INFINITY,POSITIVE_INFINITY,EPSILON,isFinite,isInteger,isNaN,isSafeInteger,MAX_SAFE_INTEGER,MIN_SAFE_INTEGER,parseFloat,parseInt,isInteger".split(","),w=0;S.length>w;w++)i(d,m=S[w])&&!i(p,m)&&l(p,m,a(d,m));(p.prototype=y).constructor=p,r(27)(e,v,p)}},function(t,n,r){var e=r(1);e(e.S,"Number",{EPSILON:Math.pow(2,-52)})},function(t,n,r){var e=r(1),i=r(3).isFinite;e(e.S,"Number",{isFinite:function(t){return"number"==typeof t&&i(t)}})},function(t,n,r){var e=r(1);e(e.S,"Number",{isInteger:r(176)})},function(t,n,r){var e=r(1);e(e.S,"Number",{isNaN:function(t){return t!=t}})},function(t,n,r){var e=r(1),i=r(176),o=Math.abs;e(e.S,"Number",{isSafeInteger:function(t){return i(t)&&o(t)<=9007199254740991}})},function(t,n,r){var e=r(1);e(e.S,"Number",{MAX_SAFE_INTEGER:9007199254740991})},function(t,n,r){var e=r(1);e(e.S,"Number",{MIN_SAFE_INTEGER:-9007199254740991})},function(t,n,r){var e=r(1),i=r(188);e(e.S+e.F*(Number.parseFloat!=i),"Number",{parseFloat:i})},function(t,n,r){var e=r(1),i=r(189);e(e.S+e.F*(Number.parseInt!=i),"Number",{parseInt:i})},function(t,n,r){"use strict";var e=r(1),a=r(49),s=r(165),l=r(156),i=1..toFixed,o=Math.floor,u=[0,0,0,0,0,0],h="Number.toFixed: incorrect invocation!",v=function(t,n){for(var r=-1,e=n;++r<6;)e+=t*u[r],u[r]=e%1e7,e=o(e/1e7)},p=function(t){for(var n=6,r=0;0<=--n;)r+=u[n],u[n]=o(r/t),r=r%t*1e7},d=function(){for(var t=6,n="";0<=--t;)if(""!==n||0===t||0!==u[t]){var r=String(u[t]);n=""===n?r:n+l.call("0",7-r.length)+r}return n},y=function(t,n,r){return 0===n?r:n%2==1?y(t,n-1,r*t):y(t*t,n/2,r)};e(e.P+e.F*(!!i&&("0.000"!==8e-5.toFixed(3)||"1"!==.9.toFixed(0)||"1.25"!==1.255.toFixed(2)||"1000000000000000128"!==(0xde0b6b3a7640080).toFixed(0))||!r(4)(function(){i.call({})})),"Number",{toFixed:function(t){var n,r,e,i,o=s(this,h),u=a(t),c="",f="0";if(u<0||20<u)throw RangeError(h);if(o!=o)return"NaN";if(o<=-1e21||1e21<=o)return String(o);if(o<0&&(c="-",o=-o),1e-21<o)if(r=(n=function(t){for(var n=0,r=t;4096<=r;)n+=12,r/=4096;for(;2<=r;)n+=1,r/=2;return n}(o*y(2,69,1))-69)<0?o*y(2,-n,1):o/y(2,n,1),r*=4503599627370496,0<(n=52-n)){for(v(0,r),e=u;7<=e;)v(1e7,0),e-=7;for(v(y(10,e,1),0),e=n-1;23<=e;)p(1<<23),e-=23;p(1<<e),v(1,1),p(2),f=d()}else v(0,r),v(1<<-n,0),f=d()+l.call("0",u);return f=0<u?c+((i=f.length)<=u?"0."+l.call("0",u-i)+f:f.slice(0,i-u)+"."+f.slice(i-u)):c+f}})},function(t,n,r){"use strict";var e=r(1),i=r(4),o=r(165),u=1..toPrecision;e(e.P+e.F*(i(function(){return"1"!==u.call(1,void 0)})||!i(function(){u.call({})})),"Number",{toPrecision:function(t){var n=o(this,"Number#toPrecision: incorrect invocation!");return void 0===t?u.call(n):u.call(n,t)}})},function(t,n,r){var e=r(1);e(e.S+e.F,"Object",{assign:r(182)})},function(t,n,r){var e=r(1);e(e.S,"Object",{create:r(72)})},function(t,n,r){var e=r(1);e(e.S+e.F*!r(10),"Object",{defineProperties:r(183)})},function(t,n,r){var e=r(1);e(e.S+e.F*!r(10),"Object",{defineProperty:r(11).f})},function(t,n,r){var e=r(5),i=r(69).onFreeze;r(52)("freeze",function(n){return function(t){return n&&e(t)?n(i(t)):t}})},function(t,n,r){var e=r(33),i=r(31).f;r(52)("getOwnPropertyDescriptor",function(){return function(t,n){return i(e(t),n)}})},function(t,n,r){r(52)("getOwnPropertyNames",function(){return r(184).f})},function(t,n,r){var e=r(17),i=r(32);r(52)("getPrototypeOf",function(){return function(t){return i(e(t))}})},function(t,n,r){var e=r(5);r(52)("isExtensible",function(n){return function(t){return!!e(t)&&(!n||n(t))}})},function(t,n,r){var e=r(5);r(52)("isFrozen",function(n){return function(t){return!e(t)||!!n&&n(t)}})},function(t,n,r){var e=r(5);r(52)("isSealed",function(n){return function(t){return!e(t)||!!n&&n(t)}})},function(t,n,r){var e=r(1);e(e.S,"Object",{is:r(192)})},function(t,n,r){var e=r(17),i=r(74);r(52)("keys",function(){return function(t){return i(e(t))}})},function(t,n,r){var e=r(5),i=r(69).onFreeze;r(52)("preventExtensions",function(n){return function(t){return n&&e(t)?n(i(t)):t}})},function(t,n,r){var e=r(5),i=r(69).onFreeze;r(52)("seal",function(n){return function(t){return n&&e(t)?n(i(t)):t}})},function(t,n,r){var e=r(1);e(e.S,"Object",{setPrototypeOf:r(153).set})},function(t,n,r){"use strict";var e=r(81),i={};i[r(7)("toStringTag")]="z",i+""!="[object z]"&&r(27)(Object.prototype,"toString",function(){return"[object "+e(this)+"]"},!0)},function(t,n,r){var e=r(1),i=r(188);e(e.G+e.F*(parseFloat!=i),{parseFloat:i})},function(t,n,r){var e=r(1),i=r(189);e(e.G+e.F*(parseInt!=i),{parseInt:i})},function(t,n,r){"use strict";var e,i,o,u,c=r(68),f=r(3),a=r(47),s=r(81),l=r(1),h=r(5),v=r(21),p=r(70),d=r(71),y=r(119),g=r(158).set,b=r(150)(),x=r(151),m=r(190),S=r(133),w=r(191),_="Promise",O=f.TypeError,E=f.process,M=E&&E.versions,P=M&&M.v8||"",j=f[_],F="process"==s(E),A=function(){},I=i=x.f,L=!!function(){try{var t=j.resolve(1),n=(t.constructor={})[r(7)("species")]=function(t){t(A,A)};return(F||"function"==typeof PromiseRejectionEvent)&&t.then(A)instanceof n&&0!==P.indexOf("6.6")&&-1===S.indexOf("Chrome/66")}catch(t){}}(),N=function(t){var n;return!(!h(t)||"function"!=typeof(n=t.then))&&n},T=function(s,r){if(!s._n){s._n=!0;var e=s._c;b(function(){for(var f=s._v,a=1==s._s,t=0,n=function(t){var n,r,e,i=a?t.ok:t.fail,o=t.resolve,u=t.reject,c=t.domain;try{i?(a||(2==s._h&&C(s),s._h=1),!0===i?n=f:(c&&c.enter(),n=i(f),c&&(c.exit(),e=!0)),n===t.promise?u(O("Promise-chain cycle")):(r=N(n))?r.call(n,o,u):o(n)):u(f)}catch(t){c&&!e&&c.exit(),u(t)}};e.length>t;)n(e[t++]);s._c=[],s._n=!1,r&&!s._h&&k(s)})}},k=function(o){g.call(f,function(){var t,n,r,e=o._v,i=R(o);if(i&&(t=m(function(){F?E.emit("unhandledRejection",e,o):(n=f.onunhandledrejection)?n({promise:o,reason:e}):(r=f.console)&&r.error&&r.error("Unhandled promise rejection",e)}),o._h=F||R(o)?2:1),o._a=void 0,i&&t.e)throw t.v})},R=function(t){return 1!==t._h&&0===(t._a||t._c).length},C=function(n){g.call(f,function(){var t;F?E.emit("rejectionHandled",n):(t=f.onrejectionhandled)&&t({promise:n,reason:n._v})})},D=function(t){var n=this;n._d||(n._d=!0,(n=n._w||n)._v=t,n._s=2,n._a||(n._a=n._c.slice()),T(n,!0))},G=function(t){var r,e=this;if(!e._d){e._d=!0,e=e._w||e;try{if(e===t)throw O("Promise can't be resolved itself");(r=N(t))?b(function(){var n={_w:e,_d:!1};try{r.call(t,a(G,n,1),a(D,n,1))}catch(t){D.call(n,t)}}):(e._v=t,e._s=1,T(e,!1))}catch(t){D.call({_w:e,_d:!1},t)}}};L||(j=function(t){p(this,j,_,"_h"),v(t),e.call(this);try{t(a(G,this,1),a(D,this,1))}catch(t){D.call(this,t)}},(e=function(t){this._c=[],this._a=void 0,this._s=0,this._d=!1,this._v=void 0,this._h=0,this._n=!1}).prototype=r(76)(j.prototype,{then:function(t,n){var r=I(y(this,j));return r.ok="function"!=typeof t||t,r.fail="function"==typeof n&&n,r.domain=F?E.domain:void 0,this._c.push(r),this._a&&this._a.push(r),this._s&&T(this,!1),r.promise},catch:function(t){return this.then(void 0,t)}}),o=function(){var t=new e;this.promise=t,this.resolve=a(G,t,1),this.reject=a(D,t,1)},x.f=I=function(t){return t===j||t===u?new o(t):i(t)}),l(l.G+l.W+l.F*!L,{Promise:j}),r(83)(j,_),r(77)(_),u=r(46)[_],l(l.S+l.F*!L,_,{reject:function(t){var n=I(this);return(0,n.reject)(t),n.promise}}),l(l.S+l.F*(c||!L),_,{resolve:function(t){return w(c&&this===u?j:this,t)}}),l(l.S+l.F*!(L&&r(125)(function(t){j.all(t).catch(A)})),_,{all:function(t){var u=this,n=I(u),c=n.resolve,f=n.reject,r=m(function(){var e=[],i=0,o=1;d(t,!1,function(t){var n=i++,r=!1;e.push(void 0),o++,u.resolve(t).then(function(t){r||(r=!0,e[n]=t,--o||c(e))},f)}),--o||c(e)});return r.e&&f(r.v),n.promise},race:function(t){var n=this,r=I(n),e=r.reject,i=m(function(){d(t,!1,function(t){n.resolve(t).then(r.resolve,e)})});return i.e&&e(i.v),r.promise}})},function(t,n,r){var e=r(1),o=r(21),u=r(2),c=(r(3).Reflect||{}).apply,f=Function.apply;e(e.S+e.F*!r(4)(function(){c(function(){})}),"Reflect",{apply:function(t,n,r){var e=o(t),i=u(r);return c?c(e,n,i):f.call(e,n,i)}})},function(t,n,r){var e=r(1),c=r(72),f=r(21),a=r(2),s=r(5),i=r(4),l=r(169),h=(r(3).Reflect||{}).construct,v=i(function(){function t(){}return!(h(function(){},[],t)instanceof t)}),p=!i(function(){h(function(){})});e(e.S+e.F*(v||p),"Reflect",{construct:function(t,n){f(t),a(n);var r=arguments.length<3?t:f(arguments[2]);if(p&&!v)return h(t,n,r);if(t==r){switch(n.length){case 0:return new t;case 1:return new t(n[0]);case 2:return new t(n[0],n[1]);case 3:return new t(n[0],n[1],n[2]);case 4:return new t(n[0],n[1],n[2],n[3])}var e=[null];return e.push.apply(e,n),new(l.apply(t,e))}var i=r.prototype,o=c(s(i)?i:Object.prototype),u=Function.apply.call(t,o,n);return s(u)?u:o}})},function(t,n,r){var e=r(11),i=r(1),o=r(2),u=r(53);i(i.S+i.F*r(4)(function(){Reflect.defineProperty(e.f({},1,{value:1}),1,{value:2})}),"Reflect",{defineProperty:function(t,n,r){o(t),n=u(n,!0),o(r);try{return e.f(t,n,r),!0}catch(t){return!1}}})},function(t,n,r){var e=r(1),i=r(31).f,o=r(2);e(e.S,"Reflect",{deleteProperty:function(t,n){var r=i(o(t),n);return!(r&&!r.configurable)&&delete t[n]}})},function(t,n,r){"use strict";var e=r(1),i=r(2),o=function(t){this._t=i(t),this._i=0;var n,r=this._k=[];for(n in t)r.push(n)};r(146)(o,"Object",function(){var t,n=this._k;do{if(this._i>=n.length)return{value:void 0,done:!0}}while(!((t=n[this._i++])in this._t));return{value:t,done:!1}}),e(e.S,"Reflect",{enumerate:function(t){return new o(t)}})},function(t,n,r){var e=r(31),i=r(1),o=r(2);i(i.S,"Reflect",{getOwnPropertyDescriptor:function(t,n){return e.f(o(t),n)}})},function(t,n,r){var e=r(1),i=r(32),o=r(2);e(e.S,"Reflect",{getPrototypeOf:function(t){return i(o(t))}})},function(t,n,r){var u=r(31),c=r(32),f=r(30),e=r(1),a=r(5),s=r(2);e(e.S,"Reflect",{get:function t(n,r){var e,i,o=arguments.length<3?n:arguments[2];return s(n)===o?n[r]:(e=u.f(n,r))?f(e,"value")?e.value:void 0!==e.get?e.get.call(o):void 0:a(i=c(n))?t(i,r,o):void 0}})},function(t,n,r){var e=r(1);e(e.S,"Reflect",{has:function(t,n){return n in t}})},function(t,n,r){var e=r(1),i=r(2),o=Object.isExtensible;e(e.S,"Reflect",{isExtensible:function(t){return i(t),!o||o(t)}})},function(t,n,r){var e=r(1);e(e.S,"Reflect",{ownKeys:r(187)})},function(t,n,r){var e=r(1),i=r(2),o=Object.preventExtensions;e(e.S,"Reflect",{preventExtensions:function(t){i(t);try{return o&&o(t),!0}catch(t){return!1}}})},function(t,n,r){var e=r(1),i=r(153);i&&e(e.S,"Reflect",{setPrototypeOf:function(t,n){i.check(t,n);try{return i.set(t,n),!0}catch(t){return!1}}})},function(t,n,r){var f=r(11),a=r(31),s=r(32),l=r(30),e=r(1),h=r(75),v=r(2),p=r(5);e(e.S,"Reflect",{set:function t(n,r,e){var i,o,u=arguments.length<4?n:arguments[3],c=a.f(v(n),r);if(!c){if(p(o=s(n)))return t(o,r,e,u);c=h(0)}if(l(c,"value")){if(!1===c.writable||!p(u))return!1;if(i=a.f(u,r)){if(i.get||i.set||!1===i.writable)return!1;i.value=e,f.f(u,r,i)}else f.f(u,r,h(0,e));return!0}return void 0!==c.set&&(c.set.call(u,e),!0)}})},function(t,n,r){var e=r(3),o=r(144),i=r(11).f,u=r(73).f,c=r(124),f=r(115),a=e.RegExp,s=a,l=a.prototype,h=/a/g,v=/a/g,p=new a(h)!==h;if(r(10)&&(!p||r(4)(function(){return v[r(7)("match")]=!1,a(h)!=h||a(v)==v||"/a/i"!=a(h,"i")}))){a=function(t,n){var r=this instanceof a,e=c(t),i=void 0===n;return!r&&e&&t.constructor===a&&i?t:o(p?new s(e&&!i?t.source:t,n):s((e=t instanceof a)?t.source:t,e&&i?f.call(t):n),r?this:l,a)};for(var d=function(n){n in a||i(a,n,{configurable:!0,get:function(){return s[n]},set:function(t){s[n]=t}})},y=u(s),g=0;y.length>g;)d(y[g++]);(l.constructor=a).prototype=l,r(27)(e,"RegExp",a)}r(77)("RegExp")},function(t,n,r){"use strict";var l=r(2),h=r(8),v=r(136),p=r(128);r(122)("match",1,function(e,i,a,s){return[function(t){var n=e(this),r=null==t?void 0:t[i];return void 0!==r?r.call(t,n):new RegExp(t)[i](String(n))},function(t){var n=s(a,t,this);if(n.done)return n.value;var r=l(t),e=String(this);if(!r.global)return p(r,e);for(var i,o=r.unicode,u=[],c=r.lastIndex=0;null!==(i=p(r,e));){var f=String(i[0]);""===(u[c]=f)&&(r.lastIndex=v(e,h(r.lastIndex),o)),c++}return 0===c?null:u}]})},function(t,n,r){"use strict";var O=r(2),e=r(17),E=r(8),M=r(49),P=r(136),j=r(128),F=Math.max,A=Math.min,h=Math.floor,v=/\$([$&`']|\d\d?|<[^>]*>)/g,p=/\$([$&`']|\d\d?)/g;r(122)("replace",2,function(i,o,S,w){function _(o,u,c,f,a,t){var s=c+o.length,l=f.length,n=p;return void 0!==a&&(a=e(a),n=v),S.call(t,n,function(t,n){var r;switch(n.charAt(0)){case"$":return"$";case"&":return o;case"`":return u.slice(0,c);case"'":return u.slice(s);case"<":r=a[n.slice(1,-1)];break;default:var e=+n;if(0===e)return t;if(l<e){var i=h(e/10);return 0===i?t:i<=l?void 0===f[i-1]?n.charAt(1):f[i-1]+n.charAt(1):t}r=f[e-1]}return void 0===r?"":r})}return[function(t,n){var r=i(this),e=null==t?void 0:t[o];return void 0!==e?e.call(t,r,n):S.call(String(r),t,n)},function(t,n){var r=w(S,t,this,n);if(r.done)return r.value;var e=O(t),i=String(this),o="function"==typeof n;o||(n=String(n));var u,c=e.global;if(c){var f=e.unicode;e.lastIndex=0}for(var a=[];;){var s=j(e,i);if(null===s)break;if(a.push(s),!c)break;""===String(s[0])&&(e.lastIndex=P(i,E(e.lastIndex),f))}for(var l="",h=0,v=0;v<a.length;v++){s=a[v];for(var p=String(s[0]),d=F(A(M(s.index),i.length),0),y=[],g=1;g<s.length;g++)y.push(void 0===(u=s[g])?u:String(u));var b=s.groups;if(o){var x=[p].concat(y,d,i);void 0!==b&&x.push(b);var m=String(n.apply(void 0,x))}else m=_(p,i,d,y,b,n);h<=d&&(l+=i.slice(h,d)+m,h=d+p.length)}return l+i.slice(h)}]})},function(t,n,r){"use strict";var f=r(2),a=r(192),s=r(128);r(122)("search",1,function(e,i,u,c){return[function(t){var n=e(this),r=null==t?void 0:t[i];return void 0!==r?r.call(t,n):new RegExp(t)[i](String(n))},function(t){var n=c(u,t,this);if(n.done)return n.value;var r=f(t),e=String(this),i=r.lastIndex;a(i,0)||(r.lastIndex=0);var o=s(r,e);return a(r.lastIndex,i)||(r.lastIndex=i),null===o?-1:o.index}]})},function(t,n,r){"use strict";var l=r(124),x=r(2),m=r(119),S=r(136),w=r(8),_=r(128),h=r(152),e=r(4),O=Math.min,v=[].push,u="split",p="length",d="lastIndex",E=4294967295,M=!e(function(){RegExp(E,"y")});r(122)("split",2,function(i,o,y,g){var b;return b="c"=="abbc"[u](/(b)*/)[1]||4!="test"[u](/(?:)/,-1)[p]||2!="ab"[u](/(?:ab)*/)[p]||4!="."[u](/(.?)(.?)/)[p]||1<"."[u](/()()/)[p]||""[u](/.?/)[p]?function(t,n){var r=String(this);if(void 0===t&&0===n)return[];if(!l(t))return y.call(r,t,n);for(var e,i,o,u=[],c=(t.ignoreCase?"i":"")+(t.multiline?"m":"")+(t.unicode?"u":"")+(t.sticky?"y":""),f=0,a=void 0===n?E:n>>>0,s=new RegExp(t.source,c+"g");(e=h.call(s,r))&&!(f<(i=s[d])&&(u.push(r.slice(f,e.index)),1<e[p]&&e.index<r[p]&&v.apply(u,e.slice(1)),o=e[0][p],f=i,u[p]>=a));)s[d]===e.index&&s[d]++;return f===r[p]?!o&&s.test("")||u.push(""):u.push(r.slice(f)),u[p]>a?u.slice(0,a):u}:"0"[u](void 0,0)[p]?function(t,n){return void 0===t&&0===n?[]:y.call(this,t,n)}:y,[function(t,n){var r=i(this),e=null==t?void 0:t[o];return void 0!==e?e.call(t,r,n):b.call(String(r),t,n)},function(t,n){var r=g(b,t,this,n,b!==y);if(r.done)return r.value;var e=x(t),i=String(this),o=m(e,RegExp),u=e.unicode,c=(e.ignoreCase?"i":"")+(e.multiline?"m":"")+(e.unicode?"u":"")+(M?"y":"g"),f=new o(M?e:"^(?:"+e.source+")",c),a=void 0===n?E:n>>>0;if(0===a)return[];if(0===i.length)return null===_(f,i)?[i]:[];for(var s=0,l=0,h=[];l<i.length;){f.lastIndex=M?l:0;var v,p=_(f,M?i:i.slice(l));if(null===p||(v=O(w(f.lastIndex+(M?0:l)),i.length))===s)l=S(i,l,u);else{if(h.push(i.slice(s,l)),h.length===a)return h;for(var d=1;d<=p.length-1;d++)if(h.push(p[d]),h.length===a)return h;l=s=v}}return h.push(i.slice(s)),h}]})},function(t,n,r){"use strict";r(198);var e=r(2),i=r(115),o=r(10),u="toString",c=/./[u],f=function(t){r(27)(RegExp.prototype,u,t,!0)};r(4)(function(){return"/a/b"!=c.call({source:"a",flags:"b"})})?f(function(){var t=e(this);return"/".concat(t.source,"/","flags"in t?t.flags:!o&&t instanceof RegExp?i.call(t):void 0)}):c.name!=u&&f(function(){return c.call(this)})},function(t,n,r){"use strict";r(28)("anchor",function(n){return function(t){return n(this,"a","name",t)}})},function(t,n,r){"use strict";r(28)("big",function(t){return function(){return t(this,"big","","")}})},function(t,n,r){"use strict";r(28)("blink",function(t){return function(){return t(this,"blink","","")}})},function(t,n,r){"use strict";r(28)("bold",function(t){return function(){return t(this,"b","","")}})},function(t,n,r){"use strict";var e=r(1),i=r(131)(!1);e(e.P,"String",{codePointAt:function(t){return i(this,t)}})},function(t,n,r){"use strict";var e=r(1),u=r(8),c=r(155),f="endsWith",a=""[f];e(e.P+e.F*r(142)(f),"String",{endsWith:function(t){var n=c(this,t,f),r=1<arguments.length?arguments[1]:void 0,e=u(n.length),i=void 0===r?e:Math.min(u(r),e),o=String(t);return a?a.call(n,o,i):n.slice(i-o.length,i)===o}})},function(t,n,r){"use strict";r(28)("fixed",function(t){return function(){return t(this,"tt","","")}})},function(t,n,r){"use strict";r(28)("fontcolor",function(n){return function(t){return n(this,"font","color",t)}})},function(t,n,r){"use strict";r(28)("fontsize",function(n){return function(t){return n(this,"font","size",t)}})},function(t,n,r){var e=r(1),o=r(78),u=String.fromCharCode,i=String.fromCodePoint;e(e.S+e.F*(!!i&&1!=i.length),"String",{fromCodePoint:function(t){for(var n,r=[],e=arguments.length,i=0;i<e;){if(n=+arguments[i++],o(n,1114111)!==n)throw RangeError(n+" is not a valid code point");r.push(n<65536?u(n):u(55296+((n-=65536)>>10),n%1024+56320))}return r.join("")}})},function(t,n,r){"use strict";var e=r(1),i=r(155);e(e.P+e.F*r(142)("includes"),"String",{includes:function(t){return!!~i(this,t,"includes").indexOf(t,1<arguments.length?arguments[1]:void 0)}})},function(t,n,r){"use strict";r(28)("italics",function(t){return function(){return t(this,"i","","")}})},function(t,n,r){"use strict";var e=r(131)(!0);r(147)(String,"String",function(t){this._t=String(t),this._i=0},function(){var t,n=this._t,r=this._i;return r>=n.length?{value:void 0,done:!0}:(t=e(n,r),this._i+=t.length,{value:t,done:!1})})},function(t,n,r){"use strict";r(28)("link",function(n){return function(t){return n(this,"a","href",t)}})},function(t,n,r){var e=r(1),u=r(33),c=r(8);e(e.S,"String",{raw:function(t){for(var n=u(t.raw),r=c(n.length),e=arguments.length,i=[],o=0;o<r;)i.push(String(n[o++])),o<e&&i.push(String(arguments[o]));return i.join("")}})},function(t,n,r){var e=r(1);e(e.P,"String",{repeat:r(156)})},function(t,n,r){"use strict";r(28)("small",function(t){return function(){return t(this,"small","","")}})},function(t,n,r){"use strict";var e=r(1),i=r(8),o=r(155),u="startsWith",c=""[u];e(e.P+e.F*r(142)(u),"String",{startsWith:function(t){var n=o(this,t,u),r=i(Math.min(1<arguments.length?arguments[1]:void 0,n.length)),e=String(t);return c?c.call(n,e,r):n.slice(r,r+e.length)===e}})},function(t,n,r){"use strict";r(28)("strike",function(t){return function(){return t(this,"strike","","")}})},function(t,n,r){"use strict";r(28)("sub",function(t){return function(){return t(this,"sub","","")}})},function(t,n,r){"use strict";r(28)("sup",function(t){return function(){return t(this,"sup","","")}})},function(t,n,r){"use strict";r(84)("trim",function(t){return function(){return t(this,3)}})},function(t,n,r){"use strict";var e=r(3),u=r(30),i=r(10),o=r(1),c=r(27),f=r(69).KEY,a=r(4),s=r(118),l=r(83),h=r(79),v=r(7),p=r(195),d=r(160),y=r(218),g=r(123),b=r(2),x=r(5),m=r(17),S=r(33),w=r(53),_=r(75),O=r(72),E=r(184),M=r(31),P=r(127),j=r(11),F=r(74),A=M.f,I=j.f,L=E.f,N=e.Symbol,T=e.JSON,k=T&&T.stringify,R="prototype",C=v("_hidden"),D=v("toPrimitive"),G={}.propertyIsEnumerable,W=s("symbol-registry"),U=s("symbols"),V=s("op-symbols"),B=Object[R],q="function"==typeof N&&!!P.f,z=e.QObject,K=!z||!z[R]||!z[R].findChild,H=i&&a(function(){return 7!=O(I({},"a",{get:function(){return I(this,"a",{value:7}).a}})).a})?function(t,n,r){var e=A(B,n);e&&delete B[n],I(t,n,r),e&&t!==B&&I(B,n,e)}:I,J=function(t){var n=U[t]=O(N[R]);return n._k=t,n},$=q&&"symbol"==typeof N.iterator?function(t){return"symbol"==typeof t}:function(t){return t instanceof N},Y=function(t,n,r){return t===B&&Y(V,n,r),b(t),n=w(n,!0),b(r),u(U,n)?(r.enumerable?(u(t,C)&&t[C][n]&&(t[C][n]=!1),r=O(r,{enumerable:_(0,!1)})):(u(t,C)||I(t,C,_(1,{})),t[C][n]=!0),H(t,n,r)):I(t,n,r)},X=function(t,n){b(t);for(var r,e=y(n=S(n)),i=0,o=e.length;i<o;)Y(t,r=e[i++],n[r]);return t},Q=function(t){var n=G.call(this,t=w(t,!0));return!(this===B&&u(U,t)&&!u(V,t))&&(!(n||!u(this,t)||!u(U,t)||u(this,C)&&this[C][t])||n)},Z=function(t,n){if(t=S(t),n=w(n,!0),t!==B||!u(U,n)||u(V,n)){var r=A(t,n);return!r||!u(U,n)||u(t,C)&&t[C][n]||(r.enumerable=!0),r}},tt=function(t){for(var n,r=L(S(t)),e=[],i=0;r.length>i;)u(U,n=r[i++])||n==C||n==f||e.push(n);return e},nt=function(t){for(var n,r=t===B,e=L(r?V:S(t)),i=[],o=0;e.length>o;)!u(U,n=e[o++])||r&&!u(B,n)||i.push(U[n]);return i};q||(c((N=function(){if(this instanceof N)throw TypeError("Symbol is not a constructor!");var n=h(0<arguments.length?arguments[0]:void 0),r=function(t){this===B&&r.call(V,t),u(this,C)&&u(this[C],n)&&(this[C][n]=!1),H(this,n,_(1,t))};return i&&K&&H(B,n,{configurable:!0,set:r}),J(n)})[R],"toString",function(){return this._k}),M.f=Z,j.f=Y,r(73).f=E.f=tt,r(117).f=Q,P.f=nt,i&&!r(68)&&c(B,"propertyIsEnumerable",Q,!0),p.f=function(t){return J(v(t))}),o(o.G+o.W+o.F*!q,{Symbol:N});for(var rt="hasInstance,isConcatSpreadable,iterator,match,replace,search,species,split,toPrimitive,toStringTag,unscopables".split(","),et=0;rt.length>et;)v(rt[et++]);for(var it=F(v.store),ot=0;it.length>ot;)d(it[ot++]);o(o.S+o.F*!q,"Symbol",{for:function(t){return u(W,t+="")?W[t]:W[t]=N(t)},keyFor:function(t){if(!$(t))throw TypeError(t+" is not a symbol!");for(var n in W)if(W[n]===t)return n},useSetter:function(){K=!0},useSimple:function(){K=!1}}),o(o.S+o.F*!q,"Object",{create:function(t,n){return void 0===n?O(t):X(O(t),n)},defineProperty:Y,defineProperties:X,getOwnPropertyDescriptor:Z,getOwnPropertyNames:tt,getOwnPropertySymbols:nt});var ut=a(function(){P.f(1)});o(o.S+o.F*ut,"Object",{getOwnPropertySymbols:function(t){return P.f(m(t))}}),T&&o(o.S+o.F*(!q||a(function(){var t=N();return"[null]"!=k([t])||"{}"!=k({a:t})||"{}"!=k(Object(t))})),"JSON",{stringify:function(t){for(var n,r,e=[t],i=1;arguments.length>i;)e.push(arguments[i++]);if(r=n=e[1],(x(n)||void 0!==t)&&!$(t))return g(n)||(n=function(t,n){if("function"==typeof r&&(n=r.call(this,t,n)),!$(n))return n}),e[1]=n,k.apply(T,e)}}),N[R][D]||r(26)(N[R],D,N[R].valueOf),l(N,"Symbol"),l(Math,"Math",!0),l(e.JSON,"JSON",!0)},function(t,n,r){"use strict";var e=r(1),i=r(132),o=r(159),a=r(2),s=r(78),l=r(8),u=r(5),c=r(3).ArrayBuffer,h=r(119),v=o.ArrayBuffer,p=o.DataView,f=i.ABV&&c.isView,d=v.prototype.slice,y=i.VIEW,g="ArrayBuffer";e(e.G+e.W+e.F*(c!==v),{ArrayBuffer:v}),e(e.S+e.F*!i.CONSTR,g,{isView:function(t){return f&&f(t)||u(t)&&y in t}}),e(e.P+e.U+e.F*r(4)(function(){return!new v(2).slice(1,void 0).byteLength}),g,{slice:function(t,n){if(void 0!==d&&void 0===n)return d.call(a(this),t);for(var r=a(this).byteLength,e=s(t,r),i=s(void 0===n?r:n,r),o=new(h(this,v))(l(i-e)),u=new p(this),c=new p(o),f=0;e<i;)c.setUint8(f++,u.getUint8(e++));return o}}),r(77)(g)},function(t,n,r){var e=r(1);e(e.G+e.W+e.F*!r(132).ABV,{DataView:r(159).DataView})},function(t,n,r){r(57)("Float32",4,function(e){return function(t,n,r){return e(this,t,n,r)}})},function(t,n,r){r(57)("Float64",8,function(e){return function(t,n,r){return e(this,t,n,r)}})},function(t,n,r){r(57)("Int16",2,function(e){return function(t,n,r){return e(this,t,n,r)}})},function(t,n,r){r(57)("Int32",4,function(e){return function(t,n,r){return e(this,t,n,r)}})},function(t,n,r){r(57)("Int8",1,function(e){return function(t,n,r){return e(this,t,n,r)}})},function(t,n,r){r(57)("Uint16",2,function(e){return function(t,n,r){return e(this,t,n,r)}})},function(t,n,r){r(57)("Uint32",4,function(e){return function(t,n,r){return e(this,t,n,r)}})},function(t,n,r){r(57)("Uint8",1,function(e){return function(t,n,r){return e(this,t,n,r)}})},function(t,n,r){r(57)("Uint8",1,function(e){return function(t,n,r){return e(this,t,n,r)}},!0)},function(t,n,r){"use strict";var e=r(172),i=r(80);r(121)("WeakSet",function(t){return function(){return t(this,0<arguments.length?arguments[0]:void 0)}},{add:function(t){return e.def(i(this,"WeakSet"),t,!0)}},e,!1,!0)},function(t,n,r){"use strict";var e=r(1),i=r(173),o=r(17),u=r(8),c=r(21),f=r(138);e(e.P,"Array",{flatMap:function(t){var n,r,e=o(this);return c(t),n=u(e.length),r=f(e,0),i(r,e,e,n,0,1,t,arguments[1]),r}}),r(67)("flatMap")},function(t,n,r){"use strict";var e=r(1),i=r(173),o=r(17),u=r(8),c=r(49),f=r(138);e(e.P,"Array",{flatten:function(){var t=arguments[0],n=o(this),r=u(n.length),e=f(n,0);return i(e,n,n,r,0,void 0===t?1:c(t)),e}}),r(67)("flatten")},function(t,n,r){"use strict";var e=r(1),i=r(120)(!0);e(e.P,"Array",{includes:function(t){return i(this,t,1<arguments.length?arguments[1]:void 0)}}),r(67)("includes")},function(t,n,r){var e=r(1),i=r(150)(),o=r(3).process,u="process"==r(45)(o);e(e.G,{asap:function(t){var n=u&&o.domain;i(n?n.bind(t):t)}})},function(t,n,r){var e=r(1),i=r(45);e(e.S,"Error",{isError:function(t){return"Error"===i(t)}})},function(t,n,r){var e=r(1);e(e.G,{global:r(3)})},function(t,n,r){r(129)("Map")},function(t,n,r){r(130)("Map")},function(t,n,r){var e=r(1);e(e.P+e.R,"Map",{toJSON:r(171)("Map")})},function(t,n,r){var e=r(1);e(e.S,"Math",{clamp:function(t,n,r){return Math.min(r,Math.max(n,t))}})},function(t,n,r){var e=r(1);e(e.S,"Math",{DEG_PER_RAD:Math.PI/180})},function(t,n,r){var e=r(1),i=180/Math.PI;e(e.S,"Math",{degrees:function(t){return t*i}})},function(t,n,r){var e=r(1),o=r(181),u=r(179);e(e.S,"Math",{fscale:function(t,n,r,e,i){return u(o(t,n,r,e,i))}})},function(t,n,r){var e=r(1);e(e.S,"Math",{iaddh:function(t,n,r,e){var i=t>>>0,o=r>>>0;return(n>>>0)+(e>>>0)+((i&o|(i|o)&~(i+o>>>0))>>>31)|0}})},function(t,n,r){var e=r(1);e(e.S,"Math",{imulh:function(t,n){var r=+t,e=+n,i=65535&r,o=65535&e,u=r>>16,c=e>>16,f=(u*o>>>0)+(i*o>>>16);return u*c+(f>>16)+((i*c>>>0)+(65535&f)>>16)}})},function(t,n,r){var e=r(1);e(e.S,"Math",{isubh:function(t,n,r,e){var i=t>>>0,o=r>>>0;return(n>>>0)-(e>>>0)-((~i&o|~(i^o)&i-o>>>0)>>>31)|0}})},function(t,n,r){var e=r(1);e(e.S,"Math",{RAD_PER_DEG:180/Math.PI})},function(t,n,r){var e=r(1),i=Math.PI/180;e(e.S,"Math",{radians:function(t){return t*i}})},function(t,n,r){var e=r(1);e(e.S,"Math",{scale:r(181)})},function(t,n,r){var e=r(1);e(e.S,"Math",{signbit:function(t){return(t=+t)!=t?t:0==t?1/t==1/0:0<t}})},function(t,n,r){var e=r(1);e(e.S,"Math",{umulh:function(t,n){var r=+t,e=+n,i=65535&r,o=65535&e,u=r>>>16,c=e>>>16,f=(u*o>>>0)+(i*o>>>16);return u*c+(f>>>16)+((i*c>>>0)+(65535&f)>>>16)}})},function(t,n,r){"use strict";var e=r(1),i=r(17),o=r(21),u=r(11);r(10)&&e(e.P+r(126),"Object",{__defineGetter__:function(t,n){u.f(i(this),t,{get:o(n),enumerable:!0,configurable:!0})}})},function(t,n,r){"use strict";var e=r(1),i=r(17),o=r(21),u=r(11);r(10)&&e(e.P+r(126),"Object",{__defineSetter__:function(t,n){u.f(i(this),t,{set:o(n),enumerable:!0,configurable:!0})}})},function(t,n,r){var e=r(1),i=r(186)(!0);e(e.S,"Object",{entries:function(t){return i(t)}})},function(t,n,r){var e=r(1),f=r(187),a=r(33),s=r(31),l=r(139);e(e.S,"Object",{getOwnPropertyDescriptors:function(t){for(var n,r,e=a(t),i=s.f,o=f(e),u={},c=0;o.length>c;)void 0!==(r=i(e,n=o[c++]))&&l(u,n,r);return u}})},function(t,n,r){"use strict";var e=r(1),i=r(17),o=r(53),u=r(32),c=r(31).f;r(10)&&e(e.P+r(126),"Object",{__lookupGetter__:function(t){var n,r=i(this),e=o(t,!0);do{if(n=c(r,e))return n.get}while(r=u(r))}})},function(t,n,r){"use strict";var e=r(1),i=r(17),o=r(53),u=r(32),c=r(31).f;r(10)&&e(e.P+r(126),"Object",{__lookupSetter__:function(t){var n,r=i(this),e=o(t,!0);do{if(n=c(r,e))return n.set}while(r=u(r))}})},function(t,n,r){var e=r(1),i=r(186)(!1);e(e.S,"Object",{values:function(t){return i(t)}})},function(t,n,r){"use strict";var e=r(1),o=r(3),u=r(46),i=r(150)(),c=r(7)("observable"),f=r(21),a=r(2),s=r(70),l=r(76),h=r(26),v=r(71),p=v.RETURN,d=function(t){return null==t?void 0:f(t)},y=function(t){var n=t._c;n&&(t._c=void 0,n())},g=function(t){return void 0===t._o},b=function(t){g(t)||(t._o=void 0,y(t))},x=function(t,n){a(t),this._c=void 0,this._o=t,t=new m(this);try{var r=n(t),e=r;null!=r&&("function"==typeof r.unsubscribe?r=function(){e.unsubscribe()}:f(r),this._c=r)}catch(n){return void t.error(n)}g(this)&&y(this)};x.prototype=l({},{unsubscribe:function(){b(this)}});var m=function(t){this._s=t};m.prototype=l({},{next:function(t){var n=this._s;if(!g(n)){var r=n._o;try{var e=d(r.next);if(e)return e.call(r,t)}catch(t){try{b(n)}finally{throw t}}}},error:function(t){var n=this._s;if(g(n))throw t;var r=n._o;n._o=void 0;try{var e=d(r.error);if(!e)throw t;t=e.call(r,t)}catch(t){try{y(n)}finally{throw t}}return y(n),t},complete:function(t){var n=this._s;if(!g(n)){var r=n._o;n._o=void 0;try{var e=d(r.complete);t=e?e.call(r,t):void 0}catch(t){try{y(n)}finally{throw t}}return y(n),t}}});var S=function(t){s(this,S,"Observable","_f")._f=f(t)};l(S.prototype,{subscribe:function(t){return new x(t,this._f)},forEach:function(e){var i=this;return new(u.Promise||o.Promise)(function(t,n){f(e);var r=i.subscribe({next:function(t){try{return e(t)}catch(t){n(t),r.unsubscribe()}},error:n,complete:t})})}}),l(S,{from:function(t){var n="function"==typeof this?this:S,r=d(a(t)[c]);if(r){var e=a(r.call(t));return e.constructor===n?e:new n(function(t){return e.subscribe(t)})}return new n(function(n){var r=!1;return i(function(){if(!r){try{if(v(t,!1,function(t){if(n.next(t),r)return p})===p)return}catch(t){if(r)throw t;return void n.error(t)}n.complete()}}),function(){r=!0}})},of:function(){for(var t=0,n=arguments.length,e=new Array(n);t<n;)e[t]=arguments[t++];return new("function"==typeof this?this:S)(function(n){var r=!1;return i(function(){if(!r){for(var t=0;t<e.length;++t)if(n.next(e[t]),r)return;n.complete()}}),function(){r=!0}})}}),h(S.prototype,c,function(){return this}),e(e.G,{Observable:S}),r(77)("Observable")},function(t,n,r){"use strict";var e=r(1),i=r(46),o=r(3),u=r(119),c=r(191);e(e.P+e.R,"Promise",{finally:function(n){var r=u(this,i.Promise||o.Promise),t="function"==typeof n;return this.then(t?function(t){return c(r,n()).then(function(){return t})}:n,t?function(t){return c(r,n()).then(function(){throw t})}:n)}})},function(t,n,r){"use strict";var e=r(1),i=r(151),o=r(190);e(e.S,"Promise",{try:function(t){var n=i.f(this),r=o(t);return(r.e?n.reject:n.resolve)(r.v),n.promise}})},function(t,n,r){var e=r(56),i=r(2),o=e.key,u=e.set;e.exp({defineMetadata:function(t,n,r,e){u(t,n,i(r),o(e))}})},function(t,n,r){var e=r(56),o=r(2),u=e.key,c=e.map,f=e.store;e.exp({deleteMetadata:function(t,n){var r=arguments.length<3?void 0:u(arguments[2]),e=c(o(n),r,!1);if(void 0===e||!e.delete(t))return!1;if(e.size)return!0;var i=f.get(n);return i.delete(r),!!i.size||f.delete(n)}})},function(t,n,r){var o=r(199),u=r(167),e=r(56),i=r(2),c=r(32),f=e.keys,a=e.key,s=function(t,n){var r=f(t,n),e=c(t);if(null===e)return r;var i=s(e,n);return i.length?r.length?u(new o(r.concat(i))):i:r};e.exp({getMetadataKeys:function(t){return s(i(t),arguments.length<2?void 0:a(arguments[1]))}})},function(t,n,r){var e=r(56),i=r(2),o=r(32),u=e.has,c=e.get,f=e.key,a=function(t,n,r){if(u(t,n,r))return c(t,n,r);var e=o(n);return null!==e?a(t,e,r):void 0};e.exp({getMetadata:function(t,n){return a(t,i(n),arguments.length<3?void 0:f(arguments[2]))}})},function(t,n,r){var e=r(56),i=r(2),o=e.keys,u=e.key;e.exp({getOwnMetadataKeys:function(t){return o(i(t),arguments.length<2?void 0:u(arguments[1]))}})},function(t,n,r){var e=r(56),i=r(2),o=e.get,u=e.key;e.exp({getOwnMetadata:function(t,n){return o(t,i(n),arguments.length<3?void 0:u(arguments[2]))}})},function(t,n,r){var e=r(56),i=r(2),o=r(32),u=e.has,c=e.key,f=function(t,n,r){if(u(t,n,r))return!0;var e=o(n);return null!==e&&f(t,e,r)};e.exp({hasMetadata:function(t,n){return f(t,i(n),arguments.length<3?void 0:c(arguments[2]))}})},function(t,n,r){var e=r(56),i=r(2),o=e.has,u=e.key;e.exp({hasOwnMetadata:function(t,n){return o(t,i(n),arguments.length<3?void 0:u(arguments[2]))}})},function(t,n,r){var e=r(56),i=r(2),o=r(21),u=e.key,c=e.set;e.exp({metadata:function(r,e){return function(t,n){c(r,e,(void 0!==n?i:o)(t),u(n))}}})},function(t,n,r){r(129)("Set")},function(t,n,r){r(130)("Set")},function(t,n,r){var e=r(1);e(e.P+e.R,"Set",{toJSON:r(171)("Set")})},function(t,n,r){"use strict";var e=r(1),i=r(131)(!0);e(e.P,"String",{at:function(t){return i(this,t)}})},function(t,n,r){"use strict";var e=r(1),i=r(51),o=r(8),u=r(124),c=r(115),f=RegExp.prototype,a=function(t,n){this._r=t,this._s=n};r(146)(a,"RegExp String",function(){var t=this._r.exec(this._s);return{value:t,done:null===t}}),e(e.P,"String",{matchAll:function(t){if(i(this),!u(t))throw TypeError(t+" is not a regexp!");var n=String(this),r="flags"in f?String(t.flags):c.call(t),e=new RegExp(t.source,~r.indexOf("g")?r:"g"+r);return e.lastIndex=o(t.lastIndex),new a(e,n)}})},function(t,n,r){"use strict";var e=r(1),i=r(193),o=r(133),u=/Version\/10\.\d+(\.\d+)?( Mobile\/\w+)? Safari\//.test(o);e(e.P+e.F*u,"String",{padEnd:function(t){return i(this,t,1<arguments.length?arguments[1]:void 0,!1)}})},function(t,n,r){"use strict";var e=r(1),i=r(193),o=r(133),u=/Version\/10\.\d+(\.\d+)?( Mobile\/\w+)? Safari\//.test(o);e(e.P+e.F*u,"String",{padStart:function(t){return i(this,t,1<arguments.length?arguments[1]:void 0,!0)}})},function(t,n,r){"use strict";r(84)("trimLeft",function(t){return function(){return t(this,1)}},"trimStart")},function(t,n,r){"use strict";r(84)("trimRight",function(t){return function(){return t(this,2)}},"trimEnd")},function(t,n,r){r(160)("asyncIterator")},function(t,n,r){r(160)("observable")},function(t,n,r){var e=r(1);e(e.S,"System",{global:r(3)})},function(t,n,r){r(129)("WeakMap")},function(t,n,r){r(130)("WeakMap")},function(t,n,r){r(129)("WeakSet")},function(t,n,r){r(130)("WeakSet")},function(t,n,r){for(var e=r(162),i=r(74),o=r(27),u=r(3),c=r(26),f=r(82),a=r(7),s=a("iterator"),l=a("toStringTag"),h=f.Array,v={CSSRuleList:!0,CSSStyleDeclaration:!1,CSSValueList:!1,ClientRectList:!1,DOMRectList:!1,DOMStringList:!1,DOMTokenList:!0,DataTransferItemList:!1,FileList:!1,HTMLAllCollection:!1,HTMLCollection:!1,HTMLFormElement:!1,HTMLSelectElement:!1,MediaList:!0,MimeTypeArray:!1,NamedNodeMap:!1,NodeList:!0,PaintRequestList:!1,Plugin:!1,PluginArray:!1,SVGLengthList:!1,SVGNumberList:!1,SVGPathSegList:!1,SVGPointList:!1,SVGStringList:!1,SVGTransformList:!1,SourceBufferList:!1,StyleSheetList:!0,TextTrackCueList:!1,TextTrackList:!1,TouchList:!1},p=i(v),d=0;d<p.length;d++){var y,g=p[d],b=v[g],x=u[g],m=x&&x.prototype;if(m&&(m[s]||c(m,s,h),m[l]||c(m,l,g),f[g]=h,b))for(y in e)m[y]||o(m,y,e[y],!0)}},function(t,n,r){var e=r(1),i=r(158);e(e.G+e.B,{setImmediate:i.set,clearImmediate:i.clear})},function(t,n,r){var e=r(3),i=r(1),o=r(133),u=[].slice,c=/MSIE .\./.test(o),f=function(i){return function(t,n){var r=2<arguments.length,e=!!r&&u.call(arguments,2);return i(r?function(){("function"==typeof t?t:Function(t)).apply(this,e)}:t,n)}};i(i.G+i.B+i.F*c,{setTimeout:f(e.setTimeout),setInterval:f(e.setInterval)})},function(t,n,r){r(341),r(280),r(282),r(281),r(284),r(286),r(291),r(285),r(283),r(293),r(292),r(288),r(289),r(287),r(279),r(290),r(294),r(295),r(247),r(249),r(248),r(297),r(296),r(267),r(277),r(278),r(268),r(269),r(270),r(271),r(272),r(273),r(274),r(275),r(276),r(250),r(251),r(252),r(253),r(254),r(255),r(256),r(257),r(258),r(259),r(260),r(261),r(262),r(263),r(264),r(265),r(266),r(328),r(333),r(340),r(331),r(323),r(324),r(329),r(334),r(336),r(319),r(320),r(321),r(322),r(325),r(326),r(327),r(330),r(332),r(335),r(337),r(338),r(339),r(242),r(244),r(243),r(246),r(245),r(231),r(229),r(235),r(232),r(238),r(240),r(228),r(234),r(225),r(239),r(223),r(237),r(236),r(230),r(233),r(222),r(224),r(227),r(226),r(241),r(162),r(313),r(197),r(318),r(198),r(314),r(315),r(316),r(317),r(298),r(196),r(199),r(200),r(353),r(342),r(343),r(348),r(351),r(352),r(346),r(349),r(347),r(350),r(344),r(345),r(299),r(300),r(301),r(302),r(303),r(306),r(304),r(305),r(307),r(308),r(309),r(310),r(312),r(311),r(356),r(354),r(355),r(397),r(400),r(399),r(401),r(402),r(398),r(403),r(404),r(378),r(381),r(377),r(375),r(376),r(379),r(380),r(362),r(396),r(361),r(395),r(407),r(409),r(360),r(394),r(406),r(408),r(359),r(405),r(358),r(363),r(364),r(365),r(366),r(367),r(369),r(368),r(370),r(371),r(372),r(374),r(373),r(383),r(384),r(385),r(386),r(388),r(387),r(390),r(389),r(391),r(392),r(393),r(357),r(382),r(412),r(411),r(410),t.exports=r(46)},function(t,n){t.exports=function(t,n){if("string"==typeof n)return t.insertAdjacentHTML("afterend",n);var r=t.nextSibling;return r?t.parentNode.insertBefore(n,r):t.parentNode.appendChild(n)}}])</script><script src="/./main.a5fda8.js"></script><script>!function(){var e,t;e="/slider.27463f.js",t=document.createElement("script"),document.getElementsByTagName("body")[0].appendChild(t),t.setAttribute("src",e)}()</script>



<!--  -->

<script>
  /* 标签页标题切换 */
  var originTitle = document.title;
  var titleTime;
  document.addEventListener("visibilitychange", function () {
    if (document.hidden) {
      document.title = "(つェ⊂) 我藏好了哦~ " + originTitle;
      clearTimeout(titleTime);
    } else {
      document.title = "(*´∇｀*) 被你发现啦~ " + originTitle;
      titleTime = setTimeout(function () {
        document.title = originTitle;
      }, 2000);
    }
  });
</script>


    
<div class="tools-col" q-class="show:isShow,hide:isShow|isFalse" q-on="click:stop(e)">
  <div class="tools-nav header-menu">
    
    
      
      
      
    
      
      
      
    
      
      
      
    
    

    <ul style="width: 70%">
    
    
      
      <li style="width: 33.333333333333336%" q-on="click: openSlider(e, 'innerArchive')"><a href="javascript:void(0)" q-class="active:innerArchive">所有文章</a></li>
      
        
      
      <li style="width: 33.333333333333336%" q-on="click: openSlider(e, 'friends')"><a href="javascript:void(0)" q-class="active:friends">友链</a></li>
      
        
      
      <li style="width: 33.333333333333336%" q-on="click: openSlider(e, 'aboutme')"><a href="javascript:void(0)" q-class="active:aboutme">关于我</a></li>
      
        
    </ul>
  </div>
  <div class="tools-wrap">
    
    	<section class="tools-section tools-section-all" q-show="innerArchive">
        <div class="search-wrap">
          <input class="search-ipt" q-model="search" type="text" placeholder="find something…">
          <i class="icon-search icon" q-show="search|isEmptyStr"></i>
          <i class="icon-close icon" q-show="search|isNotEmptyStr" q-on="click:clearChose(e)"></i>
        </div>
        <div class="widget tagcloud search-tag">
          <p class="search-tag-wording">tag:</p>
          <label class="search-switch">
            <input type="checkbox" q-on="click:toggleTag(e)" q-attr="checked:showTags">
          </label>
          <ul class="article-tag-list" q-show="showTags">
             
              <li class="article-tag-list-item">
                <a href="javascript:void(0)" class="js-tag color3">面经</a>
              </li>
             
              <li class="article-tag-list-item">
                <a href="javascript:void(0)" class="js-tag color3">算法</a>
              </li>
             
              <li class="article-tag-list-item">
                <a href="javascript:void(0)" class="js-tag color2">docker</a>
              </li>
             
              <li class="article-tag-list-item">
                <a href="javascript:void(0)" class="js-tag color2">Spring</a>
              </li>
             
              <li class="article-tag-list-item">
                <a href="javascript:void(0)" class="js-tag color4">JPA</a>
              </li>
             
              <li class="article-tag-list-item">
                <a href="javascript:void(0)" class="js-tag color5">MapStruct</a>
              </li>
             
              <li class="article-tag-list-item">
                <a href="javascript:void(0)" class="js-tag color4">Jhipster</a>
              </li>
             
              <li class="article-tag-list-item">
                <a href="javascript:void(0)" class="js-tag color3">框架</a>
              </li>
             
              <li class="article-tag-list-item">
                <a href="javascript:void(0)" class="js-tag color4">多线程</a>
              </li>
             
              <li class="article-tag-list-item">
                <a href="javascript:void(0)" class="js-tag color4">面试题</a>
              </li>
             
              <li class="article-tag-list-item">
                <a href="javascript:void(0)" class="js-tag color5">设计模式</a>
              </li>
             
              <li class="article-tag-list-item">
                <a href="javascript:void(0)" class="js-tag color5">系统设计</a>
              </li>
             
              <li class="article-tag-list-item">
                <a href="javascript:void(0)" class="js-tag color1">redis</a>
              </li>
             
              <li class="article-tag-list-item">
                <a href="javascript:void(0)" class="js-tag color3">redis集群</a>
              </li>
             
              <li class="article-tag-list-item">
                <a href="javascript:void(0)" class="js-tag color3">架构</a>
              </li>
             
              <li class="article-tag-list-item">
                <a href="javascript:void(0)" class="js-tag color2">Java基础</a>
              </li>
             
              <li class="article-tag-list-item">
                <a href="javascript:void(0)" class="js-tag color1">kafka</a>
              </li>
             
              <li class="article-tag-list-item">
                <a href="javascript:void(0)" class="js-tag color1">MySQL</a>
              </li>
             
              <li class="article-tag-list-item">
                <a href="javascript:void(0)" class="js-tag color1">分布式事务</a>
              </li>
             
              <li class="article-tag-list-item">
                <a href="javascript:void(0)" class="js-tag color4">TCC</a>
              </li>
             
              <li class="article-tag-list-item">
                <a href="javascript:void(0)" class="js-tag color1">消息一致性</a>
              </li>
             
              <li class="article-tag-list-item">
                <a href="javascript:void(0)" class="js-tag color2">快速复习指南</a>
              </li>
             
              <li class="article-tag-list-item">
                <a href="javascript:void(0)" class="js-tag color4">DDD</a>
              </li>
             
              <li class="article-tag-list-item">
                <a href="javascript:void(0)" class="js-tag color5">限流算法原理及实现</a>
              </li>
             
              <li class="article-tag-list-item">
                <a href="javascript:void(0)" class="js-tag color2">enligsh learning</a>
              </li>
             
              <li class="article-tag-list-item">
                <a href="javascript:void(0)" class="js-tag color1">MySQL实战45讲</a>
              </li>
             
              <li class="article-tag-list-item">
                <a href="javascript:void(0)" class="js-tag color5">学习笔记</a>
              </li>
             
              <li class="article-tag-list-item">
                <a href="javascript:void(0)" class="js-tag color5">数据结构与算法之美</a>
              </li>
             
              <li class="article-tag-list-item">
                <a href="javascript:void(0)" class="js-tag color5">每周打卡</a>
              </li>
            
            <div class="clearfix"></div>
          </ul>
        </div>
        <ul class="search-ul">
          <p q-show="jsonFail" style="padding: 20px; font-size: 12px;">
            缺失模块。<br/>1、请确保node版本大于6.2<br/>2、在博客根目录（注意不是yilia-plus根目录）执行以下命令：<br/> npm i hexo-generator-json-content --save<br/><br/>
            3、在根目录_config.yml里添加配置：
<pre style="font-size: 12px;" q-show="jsonFail">
  jsonContent:
    meta: false
    pages: false
    posts:
      title: true
      date: true
      path: true
      text: false
      raw: false
      content: false
      slug: false
      updated: false
      comments: false
      link: false
      permalink: false
      excerpt: false
      categories: false
      tags: true
</pre>
          </p>
          <li class="search-li" q-repeat="items" q-show="isShow">
            <a q-attr="href:path|urlformat" class="search-title"><i class="icon-quo-left icon"></i><span q-text="title"></span></a>
            <p class="search-time">
              <i class="icon-calendar icon"></i>
              <span q-text="date|dateformat"></span>
            </p>
            <p class="search-tag">
              <i class="icon-price-tags icon"></i>
              <span q-repeat="tags" q-on="click:choseTag(e, name)" q-text="name|tagformat"></span>
            </p>
          </li>
        </ul>
    	</section>
    

    
    	<section class="tools-section tools-section-friends" q-show="friends">
  		
    	</section>
    

    
    	<section class="tools-section tools-section-me" q-show="aboutme">
        
          
  	  		<div class="aboutme-wrap" id="aboutme">nothing here</div>
  	  	
    	</section>
    
  </div>
  
</div>
    <!-- Root element of PhotoSwipe. Must have class pswp. -->
<div class="pswp" tabindex="-1" role="dialog" aria-hidden="true">

    <!-- Background of PhotoSwipe. 
         It's a separate element as animating opacity is faster than rgba(). -->
    <div class="pswp__bg"></div>

    <!-- Slides wrapper with overflow:hidden. -->
    <div class="pswp__scroll-wrap">

        <!-- Container that holds slides. 
            PhotoSwipe keeps only 3 of them in the DOM to save memory.
            Don't modify these 3 pswp__item elements, data is added later on. -->
        <div class="pswp__container">
            <div class="pswp__item"></div>
            <div class="pswp__item"></div>
            <div class="pswp__item"></div>
        </div>

        <!-- Default (PhotoSwipeUI_Default) interface on top of sliding area. Can be changed. -->
        <div class="pswp__ui pswp__ui--hidden">

            <div class="pswp__top-bar">

                <!--  Controls are self-explanatory. Order can be changed. -->

                <div class="pswp__counter"></div>

                <button class="pswp__button pswp__button--close" title="Close (Esc)"></button>

                <button class="pswp__button pswp__button--share" style="display:none" title="Share"></button>

                <button class="pswp__button pswp__button--fs" title="Toggle fullscreen"></button>

                <button class="pswp__button pswp__button--zoom" title="Zoom in/out"></button>

                <!-- Preloader demo http://codepen.io/dimsemenov/pen/yyBWoR -->
                <!-- element will get class pswp__preloader--active when preloader is running -->
                <div class="pswp__preloader">
                    <div class="pswp__preloader__icn">
                      <div class="pswp__preloader__cut">
                        <div class="pswp__preloader__donut"></div>
                      </div>
                    </div>
                </div>
            </div>

            <div class="pswp__share-modal pswp__share-modal--hidden pswp__single-tap">
                <div class="pswp__share-tooltip"></div> 
            </div>

            <button class="pswp__button pswp__button--arrow--left" title="Previous (arrow left)">
            </button>

            <button class="pswp__button pswp__button--arrow--right" title="Next (arrow right)">
            </button>

            <div class="pswp__caption">
                <div class="pswp__caption__center"></div>
            </div>

        </div>

    </div>

</div>
  </div>

  
  
<script type="text/javascript" src="/plugins/activate-power-mode/activate-power-mode.js"></script>
<script>
  POWERMODE.colorful = true; // make power mode colorful
  POWERMODE.shake = false; // turn off shake
  document.body.addEventListener('input', POWERMODE);
</script>

  
  <!-- <script async type="text/javascript" size="90" alpha="0.2" zIndex="0" src="/plugins/ribbon.js/ribbon.min.js"></script> -->
  
  
    <script type="text/javascript" src="/plugins/live2d-widget.js/L2Dwidget.min.js"></script>
<script type="text/javascript">
  /**
   * 完整配置请参考：https://l2dwidget.js.org/docs/class/src/index.js~L2Dwidget.html#instance-method-init
   */
  var pluginModelPath = "assets/", // 模型的文件路径，无需更改
    pluginRootPath = "/live2d_models/"; // 插件的路径，无需更改
  //特定的模型json文件名称
  var modelPathJson = {
    "epsilon2_1": "Epsilon2.1",
    "gf": "Gantzert_Felixander",
    "haru/01": "haru01",
    "haru/02": "haru02",
    "nietzsche": "nietzche"
  }

  
    var modelName = "hibiki";
  

  var modelJsonPath = "";
  if (modelPathJson[modelName]) {
    modelJsonPath = pluginRootPath + modelName + "/" + pluginModelPath + modelPathJson[modelName] +
      ".model.json";
  } else {
    modelJsonPath = pluginRootPath + modelName + "/" + pluginModelPath + modelName + ".model.json";
  }
  L2Dwidget.init({
    model: {
      jsonPath: modelJsonPath
    },
    display: {
       position: "right", 
       width: 145, 
       height: 315, 
       hOffset: 50, 
      
    },
    mobile: {
       show: false, 
       scale: 0.6 
    },
    react: {
       opacity: 0.8 
    }
  })

</script>

  
  
</body>

</html>
